[Answered ]-Dealing with dependent objects in Django templates

2👍

You are right that you cannot run arbitrary Python in a template: the syntax is defined by the template system, which is by default the Django template language (DTL).

In your specific case, there is an easy way to access the foreign key relations of a model object: use the _set keyword. The following should work:

{% for rating in user.rating_set.all %}
<!-- do stuff with rating -->
{% endfor %}

By searching for just item.ratings, it is expecting ratings to be a model field. You need to specify _set to direct it to look at foreign key models.

This case is easy: in other instances, the best option is to run the logic in the view and pass the variable to the template’s context or (non-trivial) to make your own custom template tag.

0👍

You need to use _set.all

{% for user in users %} # Where users are defined in the view/context
    {% for rating in user.rating_set.all %}
        ...
    {% endfor %}
{% endfor %}

If you have to filtering see this.

👤torm

Leave a comment