If Statement django template

43 views
Skip to first unread message

dtdave

unread,
Jan 12, 2023, 1:13:22 PM1/12/23
to Django users
I have the following relationship in a model

class Contract(models.Model):
    supplier = models.ForeignKey(
        Supplier,
        on_delete=models.CASCADE,
        verbose_name="Supplier Name",
        related_name="contract_suppliers",
    )

I am trying to include an if statement in my template but the following does not work:
{% if contract.supplier == 'IBM' %}

If I replace this with a non-foreign key item then it works fine.

Any help would be appreciated.



Peter Benjamin Ani

unread,
Jan 12, 2023, 1:24:33 PM1/12/23
to django...@googlegroups.com
why using a foreignkey then? what type of relationship is existing between the supplier and the 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4343a170-b193-4c91-aac4-8d773404353dn%40googlegroups.com.

Namanya Daniel

unread,
Jan 12, 2023, 2:53:09 PM1/12/23
to django...@googlegroups.com

Replace supplier with related_name

Peter Benjamin Ani

unread,
Jan 12, 2023, 3:39:45 PM1/12/23
to django...@googlegroups.com
Have you figured out a solution to it?

Precious Olusola

unread,
Jan 12, 2023, 4:07:27 PM1/12/23
to django...@googlegroups.com
The supplier field in contract is an instance of a Supplier object which is not a string, so comparing it to a string won't work, instead compare a field of the supplier instance in the supplier field in contract instance.

Like: {% if contract.supplier.name == "IBM"%}

Do you get it?


ASAMOAH EMMANUEL

unread,
Jan 12, 2023, 7:11:09 PM1/12/23
to django...@googlegroups.com
You can't compare the `contract.supplier` attribute directly to a string like 'IBM', because it is a foreign key to a `Supplier` model instance. Instead, you need to access the related `Supplier` model's attributes to compare them. For example, if the `Supplier` model has a `name` attribute, you can use:


{% if contract.supplier.name == 'IBM' %}
Alternatively, you could also use a `filter()` method on your `QuerySet` to filter the contracts by their supplier name before passing them to the template.

contracts = Contract.objects.filter(supplier__name='IBM')
Then you don't need to use the if statement in the template.

{% for contract in contracts %}

Reply all
Reply to author
Forward
0 new messages