If x in <listOfModels.field> syntax

点点圈 提交于 2019-12-11 13:47:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!