Home > Net >  How to filter is_active product by Backward relationship in Django templates?
How to filter is_active product by Backward relationship in Django templates?

Time:12-23

models.py

class Category(models.Model):
    name = models.CharField(max_length=100)
    
    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):
        return self.name



class Product(models.Model):
    name = models.CharField(max_length=150)
    image = models.ImageField(upload_to="product/")
    price = models.PositiveIntegerField()
    discount = models.PositiveIntegerField(blank=True, null=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.name

template

{% for category in categories %}
    {% for product in categories.product_set.all %}
        <h1> {{ product.name }} </h1>
    {% endfor %}
{% endfor %}

I want to show filter products(Those are is_active) that belong to a category in Django template.

CodePudding user response:

If you want to display the category and name of active products then:

{% for product in product.objects.all %}
   {% if product.is_active %}
   <h1> {{ product.category }} </h1>
   <h1> {{ product.name }} </h1>
   {% endif %}
   {% endfor %}

CodePudding user response:

I will suppose you have a field is_active in Product model:

{% for category in categories %}
    {% for product in category.product_set.filter(is_active=True) %}
         <h1> {{ product.name }} </h1>
    {% endfor %}
{% endfor %}
  • Related