Search code examples
djangotemplatesviewdjango-queryset

Django: Check in template if queryset is empty


I have found the solution for this but only by checking in views so far. I need to check in templates.

My view:

brands = Brand.objects.all()
for brand in brands:
    brand.products = Product.objects.filter(brand=brand.id)

And so in my template I want to show all my brands but not those which do not have any product.

{% for brand in brands %}
    {% if brand.product is not None %}
        <!-- Displays brand -->
    {% endif %}
{% endfor %}

Something like that, but the code is not None doesn't work for empty querysets and it is still displaying brands with no objects in them. What can I do?

EDIT: Sharing model as requested.

class Brand(models.Model):
    name = models.CharField(max_length=100, null=False)

    def __str__(self):
        return self.name


class Product(models.Model):
    name = models.CharField(max_length=100, null=False)
    brand = models.IntegerField(null=True)
    price = models.DecimalField(max_digits=12, decimal_places=2, null=False)

    def __str__(self):
        return self.name

Solution

  • Your template should be like:

    {% for brand in brands %}
        {% if brand.product %}
            <!-- Displays brand -->
        {% endif %}
    {% endfor %}