分享

Django sql in查询

 怎么了啊早上 2014-04-24

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?

asked Dec 23 '10 at 23:42
Turbo
73921123
add comment

4 Answers

up vote 37 down vote accepted

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.

answered Aug 26 '11 at 4:49
Harph
505512

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约