有没有办法构造一个代表 EmptyQueryset 的 Q 对象,即始终返回空结果?

发布于 2024-10-22 05:28:04 字数 548 浏览 1 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

舟遥客 2024-10-29 05:28:04
qList = []
try:
  objectA = ...
  qList.append(Q(foo=objectA.bar))
except ...:
  ...
 ...

result = MyOtherMdel.objects.filter(reduce(operator.or_, qList),
  **other_filter_conditions)
qList = []
try:
  objectA = ...
  qList.append(Q(foo=objectA.bar))
except ...:
  ...
 ...

result = MyOtherMdel.objects.filter(reduce(operator.or_, qList),
  **other_filter_conditions)
人海汹涌 2024-10-29 05:28:04

对于查询集,有 none() 方法,它始终返回 EmptyQueryset。 Q 对象有类似的东西吗?

Q(pk=-1)

For Querysets there is the none() method, which always returns the EmptyQueryset. Is there something similar for Q objects?

Q(pk=-1)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文