Django: List Products Of Each Categories In A Page
I have a few categories and I would like to list the products per category in the format below (categories is an FK to products): Category 1 bunch of products .... Category N bunch
Solution 1:
It should be category
instead of categories
in your template. And in your model filter products by category title.
@property
def get_products(self):
return Products.objects.filter(categories__title=self.title)
{% extends 'base.html' %}
{% block content %}
{% for category in categories %}
<h1> {{category}} </h1>
{% for product in category.get_products %}
<p> {{product}} </p>
{% endfor %}
{% endfor %}
{% endblock %}
Solution 2:
You could remove the related_name
attribute from your field
class Products(models.Model):
categories = models.ForeignKey(Category, blank=True, on_delete=models.CASCADE)
And then in your template you can use category.products_set.all
{% extends 'base.html' %}
{% block content %}
{% for category in categories %}
<h1>{{ category }}</h1>
{% for product in category.products_set.all %}
<p>{{ product }}</p>
{% endfor %}
{% endfor %}
{% endblock %}
Post a Comment for "Django: List Products Of Each Categories In A Page"