Search code examples
djangocomparefieldmodels

Django checking if model fields are equal


So I got this

{% if articulo.Tipos == sth.tipo %}
    Equal
{% else %}
    Not Equal
{% endif %}

But even if the fields have the same value, it doesnt return true. By the way, articulo.Tipo is the foreign key of sth.tipo , any idea why isnt it working properly ?

Models:

class Productos(models.Model):
    tipo = models.ForeignKey("TiposOpciones", null=True, blank=True, related_name='Productos_tipo')

class TiposOpciones(models.Model):
    Tipos = models.CharField(max_length=50, null=True)

Views:

tiposopciones = TiposOpciones.objects.all()
productos = Productos.objects.all()

Solution

  • try using ifequal

    {% ifequal articulo.Tipos sth.tipo|slugify %}
        Equal
    {% else %}
        Not Equal
    {% endifequal %}
    

    also i would suggest checking the datatypes of both!

    EDIT:

    you can coerce a str to an int using the add filter

    {% for item in numItems|add:"0" %}
    

    https://docs.djangoproject.com/en/dev/ref/templates/builtins/#add

    to coerce int to str just use slugify

    {{ some_int|slugify }}