3

在 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)

对于 Querysets 有一个none()方法,它总是返回 EmptyQueryset。Q 对象有类似的东西吗?

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

4

2 回答 2

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

result = MyOtherMdel.objects.filter(reduce(operator.or_, qList),
  **other_filter_conditions)
于 2011-03-17T16:30:25.707 回答
0

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

Q(pk=-1)

于 2011-03-17T20:15:30.223 回答