Django在/不在查询 [英] Django in / not in query

查看:401
本文介绍了Django在/不在查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何在django中写一个'不在'样式的查询。
例如,我正在考虑的查询结构将如下所示。

  select table1。* 
from table1
其中table1.id不在

select table2.key_to_table1
from table2
where table2.id = some_parm

django语法将如何假定模型称为table1和table2?

解决方案

table1.objects.exclude(id__in =
table2.objects.filter(your_condition).values_list('id',flat = True))



排除功能的工作原理就像您在哪里询问的 Not 对于。属性 flat = True 告诉 table2 查询返回 value_list 作为一级列表。所以...最后你从table2获取一个 ID 的列表,你将要用户定义 table1 ,这将被排除功能拒绝。


I'm trying to figure out how to write a 'not in' style query in django. For example, the query structure I'm thinking of would look like this.

select table1.* 
from table1
where table1.id not in 
(
  select table2.key_to_table1
  from table2 
  where table2.id = some_parm 
)

What would the django syntax look like assuming models called table1 and table2?

解决方案

table1.objects.exclude(id__in = table2.objects.filter(your_condition).values_list('id', flat=True))

The exclude function works like the Not operator you where asking for. The attribute flat = True tells to table2 query to return the value_list as a one level list. So... at the end you are obtaining a list of IDs from table2, which you are going to user to define the condition in table1, that will be denied by the exclude function.

这篇关于Django在/不在查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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