有没有办法构造一个代表 EmptyQueryset 的 Q 对象,即始终返回空结果?
在 django 中,我想根据其他一些对象的属性从数据库中检索对象。如果其他对象之一不存在,则它不应影响查询结果。代码如下:
from django.db.models import Q
try:
objectA = MyModel.objects.get(id = idA)
qA = Q(foo = objectA.bar)
except MyModel.DoesNot.Exist:
qA = Q(???)
try:
objectB = MyModel.objects.get(id = idB)
qB = Q(abc = objectB.xyz)
except MyModel.DoesNot.Exist:
qB = Q(???)
result = MyOtherModel.objects.filter(qA | qB, **other_filter_conditions)
对于查询集,有 none()
方法,它始终返回 EmptyQueryset。 Q 对象有类似的东西吗?
或者有更好的方法来解决我的问题吗?
In django I want to retrieve objects from the database depending on the attributes of some other objects. If one of the other objects doesn't exist, it should not influence the result of the query. The code is like this:
from django.db.models import Q
try:
objectA = MyModel.objects.get(id = idA)
qA = Q(foo = objectA.bar)
except MyModel.DoesNot.Exist:
qA = Q(???)
try:
objectB = MyModel.objects.get(id = idB)
qB = Q(abc = objectB.xyz)
except MyModel.DoesNot.Exist:
qB = Q(???)
result = MyOtherModel.objects.filter(qA | qB, **other_filter_conditions)
For Querysets there is the none()
method, which always returns the EmptyQueryset. Is there something similar for Q objects?
Or is there a better way to solve my problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Q(pk=-1)
Q(pk=-1)