DaoRodney
DaoRodney

Reputation: 37

Get data from one column in database django

I have table Users in my database:

id name last_name status
1 John Black active
2 Drake Bell disabled
3 Pep Guardiola active
4 Steve Salt active
users_data = []

I would like to get all id and all status row from this db and write to empty dict.

What kind of query should I use? Filter, get or something else?

And what if I would like to get one column, not two?

Upvotes: 2

Views: 3336

Answers (4)

Mohammad Abbasi
Mohammad Abbasi

Reputation: 93

Suppose your model name is User. For the first part of the question use this code:

User.objects.value('id', 'sataus') # to get a dictionary
User.objects.value_list('id', 'sataus') # to get a list of values

And for the second part of the question: 'And what if I would like to get one column, not two?' you can use these codes:

User.objects.values('id')  # to get a dictionary
User.objects.values_list('id')  # to get a list of values

User.objects.values('status') # to get a dictionary
User.objects.values_list('status') # to get a list of values

Upvotes: 2

abolfazlmalekahmadi
abolfazlmalekahmadi

Reputation: 278

 yourmodelname.objects.values('id','status') 

this code show you db in two column include id and status

users_data = list(yourmodelname.objects.values('id','status'))

and with this code you can show your result on dictionary

Upvotes: 2

William Afonso
William Afonso

Reputation: 96

If, you want to access the values of specific columns for all instances of a table :

id_status_list = Users.objects.values_list('id', 'status')

You can have more info here, in the official documentation

Note that Django provides an ORM to ease queries onto the database (See this page for more info on the queries) :

  • To fetch all column values of all users instances from your Users table :

users_list = Users.objects.all()

  • To fetch all column values of specific Users in the table :

active_users_list = Users.objects.filter(status="active")

  • To fetch all column values of a specific User in the table :

user_33 = Users.objects.get(pk=33)

Upvotes: 4

DrummerMann
DrummerMann

Reputation: 847

Use the .values() method:

>>> Users.objects.values('id', 'status')
[{'id': 1, 'status': 'actice'}, {}]

The result is a QuerySet which mostly behaves like a list, you can then do list(Users.objects.values('id', 'status')) to get the list object.

users_data = list(Users.objects.values('id', 'status'))

Upvotes: 1

Related Questions