[Fixed]-Querying Many to many fields in django template

43👍

In general, you can follow anything that’s an attribute or a method call with no arguments through pathing in the django template system.

For the view code above, something like

{% for objs in obj_arr %}
{% for answer in objs.answers.all %}
  {{ answer.someattribute }}
{% endfor %}
{% endfor %}

should do what you’re expecting.

(I couldn’t quite make out the specifics from your code sample, but hopefully this will illuminate what you can get into through the templates)

👤heckj

1👍

It’s also possible to register a filter like this:

models.py

class Profile(models.Model):
    options=models.ManyToManyField('Option', editable=False)

extra_tags.py

@register.filter
def does_profile_have_option(profile, option_id):
    """Returns non zero value if a profile has the option.
    Usage::

        {% if user.profile|does_profile_have_option:option.id %}
        ...
        {% endif %}
    """
    return profile.options.filter(id=option_id).count()

More info on filters can be found here https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

Leave a comment