问题
I have a model X with a ManyToMany field Y, my query returns a list of X's,
How do I do something like:
{% if A in X.Y %}
Test
{% endif %}
EDIT: X is still a querySet (I'm not iterating the set).
Thanks in advance,
回答1:
You're pretty much there. You just have to return an actual queryset:
{% if A in X.Y.all %}
Test
{% endif %}
UPDATE (based on comment)
That is not possible with template code, you need to do a filter, and the Django templating language doesn't allow passing parameters to methods. In your view, you can do:
X.objects.filter(Y=A).exists()
And pass the result into the context to be used in the template, but I'm not sure how that fits with your exact needs.
来源:https://stackoverflow.com/questions/9368386/if-x-in-listofmodels-field-syntax