prefetch_related 对象中的 Django 过滤器

Django filter in prefetch_related object

我有一个 class,我正在使用 prefetch_related。我想应用一个过滤器,以便它只显示包含产品且产品状态等于 1 的类别。

下面是我正在使用的代码,但它多次向我展示了整个区域,并呈现了 Needs 模型中的所有项目。

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='products')
    status = models.IntegerField(choices=STATUS, default=0)

    def get_absolute_url(self):
        return reverse("product", kwargs={'slug': self.slug})

views.py

class Search(LoginRequiredMixin, ListView):
    template_name = 'search/product_search.html'
    model = Product
    queryset = Product.objects.filter(status=1)
    
    def get_context_data(self, **kwargs):
            context = super(ManualSearch, self).get_context_data(**kwargs)
            areas = Area.objects.prefetch_related('need_area__category_need__products').filter(need_area__category_need__products__gt=0)

            context['areas'] = areas
            return context

product_search.html

{% for area in areas %}
<div class="border mb-4 pb-4 px-2">
    <h2 class="fw-bold my-2">{{area.title}}</h2>
    {% for need in area.need_area.all %}
        <h4 class="text-muted my-2">{{need.title}}:</h4>
        {% for product_category in need.category_need.all %}
            {% for product in product_category.products.all %}
                <a href="{{product.get_absolute_url}}" class="pe-2"><span class="rounded-pill bg-hubble text-dark f-12 p-2">{{product.title}}</span></a>
            {% endfor %}
        {% endfor %}
    {% endfor %}
</div>
{% endfor %}

您可以过滤反向关系并查看是否有关系 exists/is-null:

的任何实例
Area.objects.filter(need_area__category_need__products__isnull=False, need_area__category_need__products__status=1).distinct()

This 是一本关于关系(特别是 M2M)过滤的好书。下次问问题之前先尝试谷歌搜索。