Querying Many to many fields in django template

与世无争的帅哥 提交于 2019-11-30 13:21:45

问题


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

Models code:

  class Info(models.Model):
     xls_answer  = models.TextField(null=True,blank=True)


  class Upload(models.Model):
     access = models.IntegerField()
     info = models.ManyToManyField(Info)
     time = models.CharField(max_length=8, null=True,blank=True)
     error_flag = models.IntegerField()

     def __unicode__(self):
        return self.access

Views:

         // obj_Arr  contains all the objects of upload
        for objs in obj_Arr:
           logging.debug(objs.access)
           logging.debug(objs.time)


        return render_to_response('upload/new_index.html', {'obj_arr': obj_Arr , 'load_flag' : 2})

In template is it possible to decode the many to many field since we are passing the object

Thanks..


回答1:


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)




回答2:


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/



来源:https://stackoverflow.com/questions/3411961/querying-many-to-many-fields-in-django-template

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