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?
CodePudding user response:
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'))
CodePudding user response:
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)
CodePudding user response:
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
CodePudding user response:
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
