2011-05-16 124 views
2
+----+---------+-----------+---------------------+-----------+-----------+ 
| id | user_id | foo_id | created_at   | active |type  | 
+----+---------+-----------+---------------------+-----------+-----------+ 
| 1 |  1 |   1 | 2011-05-10 13:12:35 |   1 | 2   | 
| 7 |  5 |   2 | 2011-05-10 14:45:04 |   1 | 1   | 
| 4 |  4 |   2 | 2011-05-10 13:24:45 |   1 | 2   | 
| 8 |  6 |   2 | 2011-05-16 14:53:03 |   1 | 1   | 
| 9 |  7 |   2 | 2011-05-16 14:55:11 |   1 | 0   | 
+----+---------+-----------+---------------------+-----------+-----------+ 

这是一个在django中的UserMapper模型。 我想编写一个查询这样的:如何在django查询集中解决这个特定查询

获取所有其foo_id = 2 and type=0user_id = 6; 说的所有结果USER_ID;

select * from table where user_id = 6 and (foo_id=2 and type=6) // Such sort of query 

我怎样才能在Django查询集做..

+0

你的SQL与你想要的描述不符。你的意思是'在哪里user_id = 6或(food_id = 2和type = 6)'? – 2011-05-16 10:36:36

+0

我的意思是'其中user_id = 6'和'(food_id = 2和type = 6)' – 2011-05-16 10:42:24

+1

但是这与'where user_id = 6 and food_id = 2 and type = 6'是一样的 - 即匹配所有三个标准,所以您的示例中没有任何行将匹配。你确定这就是你的意思吗? – 2011-05-16 10:45:25

回答

5

如果你的意思是user_id=6 and type=6 and food_id=2,然后只需使用:

UserMapper.objects.filter(user_id=6, type=6, food_id=2) 

,如果你的意思是(user_id=6ortype=6 and food_id=2) ,您可以使用Q对象:

from django.db.models import Q 
UserMapper.objects.filter(Q(user_id=6) | Q(type=6, food_id=2)) 

查看更多有关Q对象的位置:http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

0
UserMapper.objects.filter(user_id=6).filter(food_id=2).filter(type=6) 
0

UserMapper.objects.filter(user=user).filter(foo=foo).filter(type=0)

其中userUser对象ID为6,fooFoo ID为2和0可以与一些Type.SOMETHING更好,而不是仅仅使用0