开发者

Django query using OR condition

开发者 https://www.devze.com 2023-01-17 10:49 出处:网络
In Django, how do you query to get two different values, like in the following? profile_setting = (pSetting.objects.get(module=\"my_mod\"开发者_运维知识库, setting_value=1) or

In Django, how do you query to get two different values, like in the following?

profile_setting = (pSetting.objects.get(module="my_mod"开发者_运维知识库, setting_value=1) or
                   pSetting.objects.get(module="my_mod", setting_value=0))


Checkout django's Q-class:

profile_setting = pSetting.objects.get(Q(module="my_mod"),\
                  Q(setting_value=1)|Q(setting_value=0))

Furthermore to improve your coding style, have a look at some coding guidelines, you should better name your model class PSetting.


Are you sure that you are grabbing only one object?

If you are trying to grab a queryset of a bunch of objects, all you need to do is chain filters together:

profile_setting = pSetting.objects.filter(module="my_mod", setting_value__in=0)
                         .filter(module="my_mod", setting_value__in=1)

However, since everything but setting_value is the same, you can simply look for a list or tuple:

profile_setting = pSetting.objects.filter(module="my_mod", setting_value__in=[0,1])

(alexdb's suggestion above is fine if and only if you are sure that you'll be getting only one object as a response to your query)


There is a Q() object for this task - look here: Complex Queries with Q() object

In example:

profile_setting = pSetting.objects.get(
    Q(module="my_mod", setting_value=1) | Q(module="my_mod", setting_value=0)
)


 profile_setting = pSetting.objects.get(module="my_mod",setting_value__in=[0,1])


For this type of query check this documentation link

and for your specific problem you can pass multiple queryset objects(Q) for queryset use | for OR condition and & for AND condition in both get() and filter() functions.

0

精彩评论

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