我想加入许多表并在同一列上过滤每个表。我的示例用于检查软删除,但是我可以想象其他应用程序,例如按特定日期进行过滤。
例如,如果我的模型是:
from django.db import models
class Members(models.Model):
name = models.CharField(max_length=255)
deleted = models.BooleanField(default=False)
class Purchases(models.Model):
member = models.ForeignKey(Members, on_delete=models.CASCADE)
item = models.ForeignKey('Items', on_delete=models.CASCADE)
deleted = models.BooleanField(default=False)
class Items(models.Model):
company = models.ForeignKey('Companies', on_delete=models.CASCADE)
deleted = models.BooleanField(default=False)
class Companies(models.Model):
deleted = models.BooleanField(default=False)
成员进行购买,购买包含物品,物品由公司制造。假设我要计算成员购买的唯一公司的数量,但是我想检查每个表以查看是否已将其删除。我可以这样做:
Members.objects.filter(
deleted=True,
purchases__deleted=True,
purchases__item__deleted=True,
purchases__item__companies__deleted=True
).annotate(num_companies=Count('purchases__item__companies', distinct=True))
但是对每列重复__deleted==True
似乎很愚蠢。在大型联接中,是否有更有效的方法以相同的方式在每个中间表上过滤相同的列?