Querying Many to many fields in django template

后端 未结 2 610
北海茫月
北海茫月 2020-12-08 23:39

This may not be relevant but just wanted to ask,

IF an object is passed from views to template and in the template will i be able to query many to many fields

<
2条回答
  •  长情又很酷
    2020-12-09 00:06

    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/

提交回复
热议问题