编程语言
首页 > 编程语言> > python-有没有办法构造一个代表EmptyQueryset的Q对象,即始终返回空结果?

python-有没有办法构造一个代表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)

对于Queryset,有none()方法,该方法始终返回EmptyQueryset. Q对象有类似的东西吗?

还是有更好的方法来解决我的问题?

解决方法:

qList = []
try:
  objectA = ...
  qList.append(Q(foo=objectA.bar))
except ...:
  ...
 ...

result = MyOtherMdel.objects.filter(reduce(operator.or_, qList),
  **other_filter_conditions)

标签:django-q,python,django
来源: https://codeday.me/bug/20191208/2092764.html