Python 在 Django 模板中查询多对多字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3411961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Querying Many to many fields in django template
提问by Hulk
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..
谢谢..
采纳答案by heckj
In general, you can follow anything that's an attribute or a method call with no arguments through pathing in the django template system.
通常,您可以通过 django 模板系统中的路径跟踪任何没有参数的属性或方法调用。
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)
(我无法从您的代码示例中完全弄清楚细节,但希望这将阐明您可以通过模板获得的内容)
回答by Kostyantyn
It's also possible to register a filter like this:
也可以像这样注册过滤器:
models.py
模型.py
class Profile(models.Model):
options=models.ManyToManyField('Option', editable=False)
extra_tags.py
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://docs.djangoproject.com/en/dev/howto/custom-template-tags/

