简体   繁体   English

在Django Orm中使用In语句

[英]Using In statement in django orm

I have 3 tables say 我有3张桌子说

Table1       Table2                   Category
======       =================        ==============
id, name     id, Table1_id, name      category_id, Table2_id, name

Now given a category_id, I have to find those names in Table1 that belongs to that category_id 现在给定一个category_id,我必须在Table1中找到属于该category_id的那些名称

The only solution that I can think of right know is to make 2 queries like this 我能想到的唯一知道的解决方案是像这样进行2个查询

similar_ids = Table2.objects.filter(category__category_id=_cat_id).values_list('id')

similar_names = Table1.objects.filter(table2__id__in=similar_ids).values_list('name').distinct()

Is their a way to do it in a single query. 是他们在单个查询中执行此操作的一种方法。

Also given the size of the 3 tables (Table1 == 30,000 rows, Table2 and Category == 125000 rows) what will be the right thing to do :- 同样给定3个表的大小(Table1 == 30,000 rows, Table2 and Category == 125000 rows) ,正确的做法是:

  1. Make a single query by joining all the tables at once 通过一次连接所有表进行单个查询
  2. breaking it into 2 parts (as above) 分成两部分(如上所述)

The way you represented your models is quite obscure from a django standpoint. 从django的角度来看,您表示模型的方式相当晦涩。 That is, it's hard to use correct related_name s in this case. 也就是说,在这种情况下很难使用正确的related_name But let's try. 但是,让我们尝试。 You would want: 您想要:

Table1.objects.filter(table2_set__category_set__id=myid).values_list('name')

Django will not generate two queries for your original query. Django不会为您的原始查询生成两个查询。 If you do table2__id__in=similar_ids, Django will automatically use a subquery. 如果执行table2__id__in = similar_ids,则Django将自动使用子查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM