如何过滤Django QuerySet的相关字段''all'或'none'

时间:2013-07-30 05:47:11

标签: python django django-queryset django-orm

E.g我的模型Cat与[{1}}的反向ForeignKey相对应。

Life

如何获得class Life(models.Model): state = models.CharField(choices=('alive', 'dead', 'unknown') cat = models.ForeignKey('animals.Cat', related_name="lives") class Cat(models.Model): name = models.CharField(max_length=12) cat_type = models.CharField(choices=('normal', 'schroedinger') ... QuerySet个没有丧生的Cat?即所有他们的生活要么处于“活着”状态,要么属于cat_type“schroedinger”并且他们的生命都没有处于“死亡”状态。

2 个答案:

答案 0 :(得分:1)

我暂时没有使用过这个API,但我相信这可以完成工作:

from django.db.models import Q

normal_and_alive = Q(cat_type="normal") & ~Q(lives__state__in=["dead", "unknown"])
schroedinger_and_not_dead = Q(cat_type="schroedinger") & ~Q(lives__state="dead")

cats = Cat.objects.filter(normal_and_alive | schroedinger_and_not_dead)

请参阅django的complex lookups with the Q() object

文档的文档

除此之外:这只会执行一个数据库查询

答案 1 :(得分:0)

cats = Cat.objects.filter(id=-1) # make it an empty queryset

temp = Cat.objects.filter(cat_type='normal')
for one in temp:
    cats |= one.lives.filter(state='alive') # set union

temp = Cat.objects.filter(cat_type='schroedinger')
for one in temp:
    cats |= one.lives.exclude(state='dead')

return cats

新答案:

cats = Cat.objects.filter(id=-1) # make it an empty queryset

temp = Cat.objects.filter(cat_type='normal')
for one in temp:
    if len(one.lives.exclude(state='alive')) == 0:
        cats |= Cat.objects.filter(id=one.id)

temp = Cat.objects.filter(cat_type='schroedinger')
for one in temp:
    if len(one.lives.filter(state='dead')) == 0:
        cats |= Cat.objects.filter(id=one.id)

return cats
相关问题