Django 使用 OR 条件进行查询
在 Django 中,如何查询以获得两个不同的值,如下所示?
profile_setting = (pSetting.objects.get(module="my_mod", setting_value=1) or
pSetting.objects.get(module="my_mod", setting_value=0))
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))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
查看 django 的
Q-class
:
此外,为了提高您的编码风格,请查看一些编码指南,您最好将模型类命名为
PSetting
。Checkout django's
Q
-class:Furthermore to improve your coding style, have a look at some coding guidelines, you should better name your model class
PSetting
.您确定您只抓取一件物体吗?
如果你试图获取一堆对象的查询集,你需要做的就是将过滤器链接在一起:
但是,由于除了setting_value之外的所有内容都是相同的,你可以简单地查找列表或元组:
(alexdb上面的建议很好当且仅当您确定只会获得一个对象作为对查询的响应)
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:
However, since everything but setting_value is the same, you can simply look for a list or tuple:
(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)
此任务有一个
Q()
对象 - 请看这里:使用 Q() 对象的复杂查询例如:
There is a
Q()
object for this task - look here: Complex Queries with Q() objectIn example:
对于这种类型的查询,请检查此文档 链接
,对于您的具体问题,您可以传递多个查询集对象(Q)
用于查询集使用 |对于 OR 条件和 & get() 和 filter() 函数中的 AND 条件。
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.