prefetch_related 中的 django 过滤空数组

django filter empty array in prefetch_related

我使用 prefetch_relatedPrefetch 为我的产品创建了区域(主类别)、需求(子类别)和产品类别(子子类别)列表。

filter_needs = Area.objects.filter(Exists(Need.objects.filter(category_need=OuterRef('pk'))))

products = Area.objects.prefetch_related(Prefetch('need_area', 
           queryset=filter_needs, to_attr='need_area__category_need__product'))
           .filter(need_area__category_need__product__isnull=False).distinct()

models.py

class Area(models.Model):
    title = models.CharField(max_length=75, blank=False)
    body = models.CharField(max_length=150, default='-', blank=False)
    publish = models.DateTimeField('publish', default=timezone.now)   

class Need(models.Model):
    title = models.CharField(max_length=75, blank=False, null=False, help_text='max 75 characters')
    body = models.CharField(max_length=150, default='-', blank=False)
    publish = models.DateTimeField(default=timezone.now)
    need_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='need_area')

class ProductCategory(models.Model):
    title = models.CharField(max_length=400, blank=False, null=False, help_text='max 400 characters')
    body = models.TextField(default='-')
    publish = models.DateTimeField('publish', default=timezone.now)
    category_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='category_area', null=True)
    category_need = models.ForeignKey(Need, on_delete=models.CASCADE, related_name='category_need', null=True)

class Product(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=400, blank=False)
    category = models.ForeignKey(ProductCategory, on_delete = models.CASCADE, blank=True, related_name='product')

现在查询呈现包含该产品但具有所有需求的所有区域(即使没有需要的产品)。如何排除所有为空的需求?

试试这个:

from django.db.models import Prefetch


Area.objects.prefetch_related(
    Prefetch(
        "need_area"
        queryset=Need.objects.filter(
            category_need__products__isnull=False,
            category_need__products__status=1,
        ).distinct(),
    )
).filter(
    need_area__category_need__products__isnull=False, 
    need_area__category_need__products__status=1,
).distinct()

您必须在自定义预取上指定与外部过滤器相同的过滤器。