Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'?

like image 323
Daryl Avatar asked Jan 27 '11 01:01

Daryl


People also ask

What is __ In Django filter?

filter(tags__in=tags) matches photos that have any of the tags, not only those that has all. Some of those that only has one of the desired tags, may have exactly the amount of tags that you are looking for, and some of those that has all the desired tags, may also have additional tags.

How can I filter a Django query with a list of values?

The sql query will be like SELECT * FROM mytable WHERE ids=[1, 3, 6, 7, 9] which is not true. You have to use in operator for this so you query will be like SELECT * FROM mytable WHERE ids in (1, 3, 6, 7, 9) for that Django provide __in operator.

What is the difference between filter and get method in Django?

Basically use get() when you want to get a single unique object, and filter() when you want to get all objects that match your lookup parameters.

What does Django objects filter return?

Django provides a filter() method which returns a subset of data. It accepts field names as keyword arguments and returns a QuerySet object. As database has only one record where name is 'tom' , the QuerySet object contains only a single record.


1 Answers

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

like image 67
Cloud Artisans Avatar answered Sep 23 '22 03:09

Cloud Artisans