在Django模板中查询多对多字段
这可能不是特别相关,但我想问一下,
如果一个对象从视图传递到模板,在模板中我能查询多对多的字段吗?
模型代码:
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})
在模板中,既然我们传递了对象,是否可以解码多对多的字段呢?
谢谢..
2 个回答
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/
43
一般来说,在Django模板系统中,你可以通过路径访问任何属性或没有参数的方法调用。
对于上面的视图代码,像下面这样
{% for objs in obj_arr %}
{% for answer in objs.answers.all %}
{{ answer.someattribute }}
{% endfor %}
{% endfor %}
应该能达到你想要的效果。
(我没能完全理解你代码示例中的具体内容,但希望这能帮助你明白通过模板可以获取哪些东西。)