开发者

how to solve this particular query in django queryset

+----+---------+-----------+---------------------+-----------+-----------+
| 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         |
+----+---------+-----------+-------------------开发者_如何学JAVA--+-----------+-----------+

This is a UserMapper model in django. I want to write a query such that:

Get all the user_id whose foo_id = 2 and type=0 and all the result of user_id = 6; Say;

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

How can I do in django query set..


If you mean user_id=6 and type=6 and food_id=2, then just use:

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

if you mean (user_id=6) or (type=6 and food_id=2), you can use the Q object :

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

See more about Q object here: http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects


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


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

where user is User object with id 6, foo is Foo with id 2 and 0 could be better with some Type.SOMETHING instead of just using 0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜