1๐
โ
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 %}
Source:stackexchange.com