本文介绍了Django:在模板中显示ManyToManyField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Django项目中有这些模型: class Area(models.Model):
name = models.CharField(max_length = 100,primary_key = True)
def __unicode __(self):
return self.name
class Place(models.Model):
id = model.IntegerField(primary_key = True)
name = models.CharField(max_length = 100,primary_key = True)
area = models.ManyToManyField(Area,related_name ='area')
如何在我的模板中显示Place的区域名称?目前我有:
{%在地点%}
名称:{{place.name}},区域:{{place.area}}
{%endfor%}
其中:
区域:< django.db.models.fields.related.ManyRelatedManager对象在0x10435a3d0>
和 {{place.area}}
只是空白任何人都可以帮忙?
解决方案
在模板中使用 place.area.all
{%在地点%}
名称:{{place.name}}< br />
区域:< br /> {%for places.area.all%} {{area}}< br /> {%endfor%}
{%endfor%}
I've got these models in my Django project:
class Area(models.Model):
name = models.CharField(max_length=100, primary_key=True)
def __unicode__(self):
return self.name
class Place(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100, primary_key=True)
area = models.ManyToManyField(Area,related_name='area')
How can I show the Place's area name(s) in my template? Currently I have:
{% for place in places %}
Name: {{ place.name }}, Area: {{ place.area}}
{% endfor %}
which gives:
Area: <django.db.models.fields.related.ManyRelatedManager object at 0x10435a3d0>
And {{ place.area}}
is just blank. Can anyone help?
解决方案
Use place.area.all in the template
http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships
{% for place in places %}
Name: {{ place.name }}<br/>
Area: <br/>{% for area in places.area.all %}{{ area }}<br/>{% endfor %}
{% endfor %}
这篇关于Django:在模板中显示ManyToManyField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!