例如,我有一个模型 Cat
,它有一个来自 Life
的反向 ForeignKey
。
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
没有失去他们的生命? IE。 所有他们的生活要么处于“活着”状态,要么是 cat_type“schroedinger”并且没有任何生活处于“死亡”状态)
最佳答案
我有一段时间没有使用这个 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)
有关 complex lookups with the Q() object 的 django 文档,请参阅文档
旁白:这只会执行一个数据库查询
关于python - 如何过滤 Django QuerySet 的相关字段' 'all' 或 'none',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17939139/