Question

I've a Django Query:-

obj = ABC.objects.filter(column1 = value)
a_list = []
for x in obj:
   a_list.append(x.column2)

I want to fetch the list of values of column2 in one go., ie dont want to use the for loop. Is there any 1 straight forward query for this?

Was it helpful?

Solution

ABC.objects.filter(column1=value).values_list('column2', flat=True)

OTHER TIPS

https://docs.djangoproject.com/en/1.6/ref/models/querysets/#values-list

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top