Django在/不在查询中
我想弄清楚如何在django中编写一个“不在”风格的查询。 例如,我正在考虑的查询结构看起来像这样。
select table1.* from table1 where table1.id not in ( select table2.key_to_table1 from table2 where table2.id = some_parm )
假设叫做table1和table2的模型,django的语法是什么样的?
table1.objects.exclude(id__in = table2.objects.filter(your_condition).values_list('id', flat=True))
排除function就像您要求的Not
运算符一样。 flat = True
属性告诉table2
查询返回value_list
作为一个级别的列表。 所以…最后你要从table2中获得一个IDs
列表,你将要用它来定义table1
的条件,这将被排除function拒绝。
与这些模型:
class table1(models.Model): field1 = models.CharField(max_length=10) # a dummy field class table2(models.Model): key_to_table1 = models.ForeignKey(table1)
你应该得到你想要的东西:
table1.objects.exclude(table2=some_param)
table1.objects.extra(where=["table1.id NOT IN (SELECT table2.key_to_table1 FROM table2 WHERE table2.id = some_parm)"])
您可以编写一个Django查询的自定义查找:
从文档 : “让我们从一个简单的自定义查找开始,我们将编写一个自定义的查找ne ,它和exact完全相反, author.objects.filter(name__ne ='Jack')将转换为SQL: "author"."name" <> 'Jack'
”
from django.db.models import Lookup class NotEqual(Lookup): lookup_name = 'ne' def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return '%s <> %s' % (lhs, rhs), params
[o1 for o1 in table1.objects.all() if o1.id not in [o2.id for o2 in table2.objects.filter(id=some_parm)]]
或更好
not_in_ids = [obj.id for obj in table2.objects.filter(id=some_parm)] selected_objects = [obj for obj in table1.objects.iterator() if obj.id not in not_in_ids]