Thomas Doll-Datema
Thomas Doll-Datema

Reputation: 178

How to skip if empty item in column in Django DB

I;m new to learning Django and ran into a small issue: I'm working on a product display page where some products are in a subcategory. I want to be able to display this subcategory when needed but I do not want it to show up when unused. Right now it will show up on my page as 'NONE' which I do not want. How do I fix this?

My model looks like this:

class Category(models.Model):
category_name = models.CharField(max_length=200)
    sub_category = models.CharField(max_length=200,blank=True,null=True)

def __str__(self):
        return f" {self.category_name} {self.sub_category}"

On my webpage I use the {{category}} in a for loop to display the different categories. Unfortunately is shows 'NONE' when there is no subcategory.

I have tried the following:

{% for category in categories  %}
<p>
    {% if category.sub_category == "NULL" %}
        {{category.category_name}}
    {% else %}
        {{category}}    
    {% endif %}
</p>
{% endfor %}

Upvotes: 1

Views: 166

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

If the value is NULL at the database side, it is None at the Django/Python side, so you can work with:

{% for category in categories %}
<p>
    {% if category.sub_category is None %}
        {{ category.category_name }}
    {% else %}
        {{ category }}
    {% endif %}
</p>
{% endfor %}

But instead of that, it makes more sense to fix this in the model itself:

class Category(models.Model):
    category_name = models.CharField(max_length=200)
    sub_category = models.CharField(max_length=200, blank=True, null=True)

    def __str__(self):
        if self.sub_category is None:
            return self.category_name
        else:
            return f'{self.category_name} {self.sub_category}'

This simplfies rendering to:

{% for category in categories %}
<p>
    {{ category }}
</p>
{% endfor %}

Upvotes: 1

Related Questions