[Fixed]-How can I limit what m2m items are displayed in django template-side?

1👍

You can’t provide filter arguments with the Django template language.

In Django 1.7+, you can use prefetch_related with a custom Prefetch object when defining the queryset in the view.

def get_queryset(self):
    ...
    parents = Parent.objects.filter(
        children__male=True
    ).prefetch_related(
        Prefetch('children', queryset=Child.objects.filter(male=True), to_attr='male_children')
    )

Note that in the example above, you probably need to use distinct() to prevent duplicated parents for each male child.

We have used the to_attr argument as recommended in the docs. In the template, we then loop through the male children.

{% for parent in parents %}
    {{ parent.name }}
    {% for child in parent.male_children %}
        {{ child }}
    {% endfor %}
{% endfor %} 

Leave a comment