+----+---------+-----------+---------------------+-----------+-----------+
| 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
模型。
我想写一个查询:
获取foo_id = 2 and type=0
以及user_id = 6;
的所有结果的所有user_id
说;
select * from table where user_id = 6 and (foo_id=2 and type=6) // Such sort of query
如何在django查询集中进行..
答案 0 :(得分:5)
如果您的意思是user_id=6 and type=6 and food_id=2
,那么只需使用:
UserMapper.objects.filter(user_id=6, type=6, food_id=2)
如果您的意思是{user_id=6
)or
(type=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
答案 1 :(得分:0)
UserMapper.objects.filter(user_id=6).filter(food_id=2).filter(type=6)
答案 2 :(得分:0)
UserMapper.objects.filter(user=user).filter(foo=foo).filter(type=0)
,
其中user
是User
对象,ID为6,foo
为Foo
,ID为2,而{0}可能更好Type.SOMETHING
而不是仅仅使用0