Vingtoft Vingtoft - 1 month ago 5
Python Question

Django: How to get parameters from QuerySet

Consider the following Django model:

class SomeModel(models.Model):
some_var = models.IntergerField()


Whats the best way to get an array of a models parameters from a search results?

Example (not working of course):

a = SomeModel.objects.all().some_var


would give something like
[3, 4, 1, 9, 1, 2]

Answer

There is existing queryset method called values_list https://docs.djangoproject.com/en/1.10/ref/models/querysets/#values-list

a = SomeModel.objects.all().values_list('some_var', flat=True)

We are using flat=True so that it will give flat list

Entry.objects.values_list('id').order_by('id')
[(1,), (2,), (3,), ...]
Entry.objects.values_list('id', flat=True).order_by('id')
[1, 2, 3, ...]