Dr Manhattan
Dr Manhattan

Reputation: 14097

How to get a list from a queryset in Django

Consider the following django code

phonenumbers = othermodel.objects.filter( company=mymodel.company,
                                         date_overwritten__isnull=True
                                       ).values_list('id', flat=True)

This is returning another QuerySet object instead of a python list, the first object in the queryset returned is a {valuesListQuerySet} which is an empty list and this is correct because my whole model/table othermodel is currently empty

What am i missing? and how do i get just the {valuesListQuerySet} as a normal python list even if its empty

Upvotes: 2

Views: 11455

Answers (1)

Luis Sobrecueva
Luis Sobrecueva

Reputation: 690

As the django doc says

If you don’t pass any values to values_list(), it will return all the fields in the model, in the order they were declared.

Note that this method returns a ValuesListQuerySet. This class behaves like a list. Most of the time this is enough, but if you require an actual Python list object, you can simply call list() on it, which will evaluate the queryset.

So you could call:

list(phonenumbers)

Upvotes: 4

Related Questions