如果多对多相关对象中的任何一个具有给定的 属性 值,则从查询集中排除对象
Exclude object from queryset if any of it's many to many related objects has a given property value
假设我有这样的模型:
class Bar(Model):
value = IntegerField()
class Foo(Model):
bars = ManyToManyField(Bar)
现在,我如何获取 Foo 对象的查询集,不包括具有任何 bars
对象且值为 0
的对象?
对应的Python代码是这样的:
foos_ids_to_exclude = []
for foo in Foo.objects.all():
for bar in foo.bars.all():
if bar.value == 0:
foos_ids_to_exclude.append(foo.id)
break
resulting_queryset = Foo.objects.exclude(id__in=foos_ids_to_exclude)
但是我如何在 DjangoORM 级别上执行此操作?甚至有可能吗?
如果可能,我想在不评估查询集的情况下执行此操作。
您可以与 .exclude(…)
[Django-doc] 合作:
Foo.objects.exclude(<b>bars__value=0</b>)
请注意,没有任何相关 Bar
的 Foo
s 仍将在查询集中。
假设我有这样的模型:
class Bar(Model):
value = IntegerField()
class Foo(Model):
bars = ManyToManyField(Bar)
现在,我如何获取 Foo 对象的查询集,不包括具有任何 bars
对象且值为 0
的对象?
对应的Python代码是这样的:
foos_ids_to_exclude = []
for foo in Foo.objects.all():
for bar in foo.bars.all():
if bar.value == 0:
foos_ids_to_exclude.append(foo.id)
break
resulting_queryset = Foo.objects.exclude(id__in=foos_ids_to_exclude)
但是我如何在 DjangoORM 级别上执行此操作?甚至有可能吗?
如果可能,我想在不评估查询集的情况下执行此操作。
您可以与 .exclude(…)
[Django-doc] 合作:
Foo.objects.exclude(<b>bars__value=0</b>)
请注意,没有任何相关 Bar
的 Foo
s 仍将在查询集中。