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 %}

On Thu, Jan 12, 2023 at 2:52 PM Namanya Daniel <dnamanya.dan...@gmail.com>
wrote:

>
> Replace supplier with related_name
>
> On Thu, 12 Jan 2023 at 16:13, 'dtdave' via Django users <
> django-users@googlegroups.com> wrote:
>
>> 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.
>>
>>
>>
>> --
>> 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+unsubscr...@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
>> <https://groups.google.com/d/msgid/django-users/4343a170-b193-4c91-aac4-8d773404353dn%40googlegroups.com?utm_medium=email&utm_source=footer>
>> .
>>
> --
> 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+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CAP4VW2V7HfijNHaCX5G_6ACmkQwLvHVXK%2BfgVdMEjTUOF8jYKA%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-users/CAP4VW2V7HfijNHaCX5G_6ACmkQwLvHVXK%2BfgVdMEjTUOF8jYKA%40mail.gmail.com?utm_medium=email&utm_source=footer>
> .
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CABFHQYw8jQObsCMUX4poRMRTtb0g0ph2f%2BjNrrdvnbfNu2Eq5Q%40mail.gmail.com.

Reply via email to