Two or more __in filters in django queryset

妖精的绣舞 提交于 2019-12-04 15:19:30

What part of this is confusing? http://docs.djangoproject.com/en/1.2/ref/models/querysets/#in It seems very clear.

It's not perfectly clear from the question what the problem is.

Are you asking how to use a multi-part key? If so, you're going to be unhappy with simple __in.

If you're trying to look for an "OR" of a two-part key, you have to create a more complex condition.

Start here: http://docs.djangoproject.com/en/1.2/topics/db/queries/#complex-lookups-with-q-objects

from django.db.models import Q
product_list.filter(
Q(productnr='OB520', supplier_id=3) | Q(productnr='RH402', supplier_id=20))

If you're trying to do multi-key lookups, this is they way it has to work.

Or, is the problem that your "in" clause has a long list of specific values?

If you have a long list, you might want to build the query in pieces.

q_obj= Q()
for p, s in some_list_of_pairs;
   q_obj |= Q(productnr=p, supplier_id=s )
product_list.filter(q_obj)

The above is untested. Also, it's probably inefficient.

What's better is something like this.

def values_iter( some_list_of_pairs ):
    for p, s in some_list_of_pairs
        yield product_list.get(productnr=p, supplier_id=s) 

That will do a number of very efficient SQL lookups one at a time. That may execute faster than building a complex multi-key IN clause.

Comma-delimit the query.

Example:

?groups__in=1,2

Sometimes it's better to answer the question rather than to bicker about it being a valid question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!