4

例如,我有Cat一个ForeignKeyLife.

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',并且他们的生命都没有处于“死亡”状态)

4

2 回答 2

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)

有关使用 Q() 对象进行复杂查找的 django 文档,请参阅文档

旁白:这只会执行一个数据库查询

于 2013-09-16T14:32:49.523 回答
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
于 2013-09-15T03:19:04.837 回答