python – 如何过滤Django QuerySet的相关字段”all’或’none’
发布时间:2020-12-20 13:36:12 所属栏目:Python 来源:网络整理
导读:例如,我有一个模型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.
例如,我有一个模型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_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) 请参阅django的文档complex lookups with the Q() object的文档 除此之外:这只会执行一个数据库查询 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |