Reputation: 26886
As all we know, we can use the model_to_dict
convert the query_set to a dictionary.
from django.forms.models import model_to_dict
u = User.objects.get(id=1)
u_dict = model_to_dict(u)
type(u)
#<class 'django.contrib.auth.models.User'>
type(u_dict)
#<type 'dict'>
But, I want to convert the query_set to a list that contains the dictionary.
uers = User.objects.all()
Here I will write a for
loop to convert the query_set to convert to dictionary. then append to a list.
So, whether there is a convenient way to convert the query_set list to my requirement?
Upvotes: 1
Views: 136
Reputation: 934
You can use .values
User.objects.values()
This returns a QuerySet. You can change to list by simply casting to list
list(User.objects.values())
Same can be used with filter
: User.objects.filter(<some filter>).values()
Upvotes: 1