Django objects.filter() values_list() vs python list comprehension for __in query

Daryl picture Daryl · Jan 27, 2011 · Viewed 38.8k times · Source

I have a quirk(?) with Django queryset filtering:

ipdb> MagazineIssue.objects.filter(id__in=l_magazines.values_list('id'))
Out[0]: []

or

ipdb> MagazineIssue.objects.filter(id__in=[l_magazine.id for l_magazine in l_magazines])
Out[0]: [<MagazineIssue: Architecture Australia, Jan 1995 (#1)>]

and

ipdb> l_magazines.values_list('id')
Out[0]: [(1,)]
ipdb> [l_magazine.id for l_magazine in l_magazines]
Out[0]: [1]

so, how to use values_list()? (to produce):

[1]

or is python list comprehension the 'way to go'?

Answer

Cloud Artisans picture Cloud Artisans · Jan 27, 2011

Try l_magazines.values_list('id', flat=True). That returns a list of ids instead of a list of single id tuples.