开发者

Is there way to construct a Q object, that represents a EmptyQueryset, i.e. that always returns an empty result?

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?


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

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


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

Q(pk=-1)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜