2011-05-16 90 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