过滤多人关系,排除有条件的孩子

问题描述 投票:2回答:1

我与类别和产品有一对多的关系,类别和产品都有活动字段,如果其中任何一个不活动我想从列表中排除它们。

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)
python django
1个回答
4
投票

如果您需要过滤相关产品,可以使用prefetc_relatedPrefetch对象:

from django.db.models import Prefetch
categories = Category.objects.filter(is_active=True).prefetch_related(Prefetch('product_set', queryset=Produc.objects.filter(is_active=True)))

在这种情况下,从categories这个代码的每个类别

category.product_set.all()

将仅返回有效产品。此外,此查询集不会命中DB,因为相关产品将通过第一个查询进行缓存。

© www.soinside.com 2019 - 2024. All rights reserved.