django查询中有两个或多个__in过滤器 [英] Two or more __in filters in django queryset

查看:474
本文介绍了django查询中有两个或多个__in过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个查询

  query ='select * from products where(productnr,supplier_id)in(%s)' %product_list 

其中product_list如下所示((OB520,3),(RH402,20).. 。)



如何在Django中使用queryset和__in过滤器执行此操作?

解决方案

这有什么困惑? http://docs.djangoproject.com/en/1.2/ref/ model / querysets /#in 看起来很清楚。



问题是什么问题不清楚。



您是否问如何使用多 - 一键?如果是这样,您将不满意中的简单 __。



如果您正在寻找两部分键的OR,则必须创建一个更复杂的条件。



从这里开始: 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))

如果您尝试进行多键查找,或者,您的in子句有很长的具体值列表的问题吗?



如果您有一个长列表,您可能需要构建查询。

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

以上是未经测试的。此外,这可能是低效的。



更好的是这样的。

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

这将一次执行一些非常高效的SQL查询。这可能比构建复杂的多键IN子句执行得更快。


I have this query

query = 'select * from products where (productnr, supplier_id) in (%s)' % product_list

where product_list looks like this ((OB520, 3),(RH402, 20)...)

How do I go about doing this in Django using queryset and the __in filter

解决方案

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.

这篇关于django查询中有两个或多个__in过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆