【问题标题】:Querying Many to many fields in django template在 django 模板中查询多对多字段
【发布时间】:2011-03-25 15:03:29
【问题描述】:

这可能不相关,只是想问一下,

如果一个对象从视图传递到模板,并且在模板中我将能够查询多对多字段

型号代码:

  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

观看次数:

         // 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})

在模板中是否可以解码多对多字段,因为我们正在传递对象

谢谢..

【问题讨论】:

    标签: python django django-models django-templates django-views


    【解决方案1】:

    也可以像这样注册过滤器:

    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()
    

    更多关于过滤器的信息可以在这里找到https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

    【讨论】:

      【解决方案2】:

      通常,您可以通过 django 模板系统中的路径跟踪任何不带参数的属性或方法调用。

      对于上面的视图代码,类似

      {% for objs in obj_arr %}
      {% for answer in objs.answers.all %}
        {{ answer.someattribute }}
      {% endfor %}
      {% endfor %}
      

      应该做你所期望的。

      (我无法从您的代码示例中完全弄清楚具体细节,但希望这将阐明您可以通过模板获得的内容)

      【讨论】:

      猜你喜欢
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 2011-04-07
      相关资源
      最近更新 更多