Python 筛选多个关系,根据条件排除子项
我与类别和产品有一对多关系,类别和产品有活动字段,如果其中任何字段不活动,我想将它们从列表中排除Python 筛选多个关系,根据条件排除子项,python,django,Python,Django,我与类别和产品有一对多关系,类别和产品有活动字段,如果其中任何字段不活动,我想将它们从列表中排除 categories = Category.objects.filter(is_active=True) 但现在类别可以有许多产品,其中一些是非活动的,我如何从所有类别中筛选和排除非活动的产品 型号: class Category(MPTTModel): name = models.CharField(max_length=50, blank=False, unique=True)
categories = Category.objects.filter(is_active=True)
但现在类别可以有许多产品,其中一些是非活动的,我如何从所有类别中筛选和排除非活动的产品
型号:
class Category(MPTTModel):
name = models.CharField(max_length=50, blank=False, unique=True)
is_active = models.BooleanField(default=True)
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', db_index=True)
class Product(models.Model):
name = models.CharField(max_length=50, blank=False, unique=True)
is_active = models.BooleanField(default=True)
category = TreeForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True, db_index=True)
如果需要筛选相关的产品,可以与预取对象一起使用: 在这种情况下,对于此代码中的每个类别
category.product_set.all()
将只返回活动产品。此外,这个查询集不会命中数据库,因为第一个查询将缓存相关的产品
category.product_set.all()