Francisco Ghelfi
Francisco Ghelfi

Reputation: 962

Django: get foreign key´s value instead of id

I´m trying to use foreign key values in a template.

When I try to show it, I get the value on screen correctly.

{% for x in dataset %}
    <p> {{ x.fieldname }}
{% endfor %}

But when I try to use it for comparisons it uses the id, not the value.

{% for x in dataset %}
    {% if x.fieldname == "The name I want" %}
        <p> {{ x.fieldname }}
    {% endif %}
{% endfor %}

I´ve been looking some posts relateing serializers with this, but (in my little knowledge) I understand serializers are to send or receive data from outside the application.

As the is only tu use the values within the application, is there another way to get the actual value for comparisons? Should I use the serializers approach?

Thanks!

Upvotes: 0

Views: 885

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476547

I think you assume too much "magic" here. If you fetch the attribute that is related to a ForeignKey, it simply fetches the related instance. Now in case you render such instance, Django will typically fallback on the __str__ of the model instance.

So what you need to do is find out how the __str__ of the model that is referenced works. For example if Model uses the .name attribute to convert it to a string, you can write:

{% if x.fieldname.name == "The name I want" %}

In case it is unknown how it is rendered, you can use the stringformat template filter:

{% if x.fieldname|stringformat:"" == "The name I want" %}

Upvotes: 1

Related Questions