I have a class where I am using prefetch_related. I'd like to apply a filter so it only shows categories that contain products and if product status is equal to 1.
Below is the code that I am using but it shows me the whole area multiple times and it renders all items from Needs
model.
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 >
<h2 >{{area.title}}</h2>
{% for need in area.need_area.all %}
<h4 >{{need.title}}:</h4>
{% for product_category in need.category_need.all %}
{% for product in product_category.products.all %}
<a href="{{product.get_absolute_url}}" ><span >{{product.title}}</span></a>
{% endfor %}
{% endfor %}
{% endfor %}
</div>
{% endfor %}
CodePudding user response:
You can filter reverse relation and see if any instances of the relation exists/is-null:
Area.objects.filter(need_area__category_need__products__isnull=False, need_area__category_need__products__status=1).distinct()
This is a good read regarding relationships (specifically M2M) filtering. Next time try googling first before asking a question.