Vingtoft Vingtoft - 1 year ago 157
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 Source

There is existing queryset method called values_list

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

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

[(1,), (2,), (3,), ...]
Entry.objects.values_list('id', flat=True).order_by('id')
[1, 2, 3, ...]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download