我在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 = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100, primary_key=True)
area = models.ManyToManyField(Area,related_name='area')
Run Code Online (Sandbox Code Playgroud)
如何在模板中显示地方的地区名称?目前我有:
{% for place in places %}
Name: {{ place.name }}, Area: {{ place.area}}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
这使:
Area: <django.db.models.fields.related.ManyRelatedManager object at 0x10435a3d0>
Run Code Online (Sandbox Code Playgroud)
而且{{ place.area}}只是空白.有人可以帮忙吗?
cro*_*jer 75
在模板中使用place.area.all
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 place.area.all %}{{ area }}<br/>{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
Joh*_*uez 12
您可以使用现有的连接模板标记.
https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#join
这是代码
{% for place in places %}
Name: {{ place.name }}, Area: {{ place.area.all|join:", " }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
你的视图代码是什么样的?
这是您可以返回相关模型的一种方法:
from myapp.models import Area, Place
def detail(request, place_id):
place = Place.objects.get(pk=place_id)
areas = place.area.all()
return render_to_response('detail.html', {
"place": place,
"areas": areas,
})
Run Code Online (Sandbox Code Playgroud)
这个例子只是为了说明;你想包括错误处理代码。
您的模板可能如下所示:
<h3>{{ place }}</h3>
{% if areas %}
<ul>
{% for area in areas %}
<li>{{ area.name }}</li>
{% endfor %}
</ul>
{% endif %}
Run Code Online (Sandbox Code Playgroud)
仅显示 ManyToMany 字段:
{% for place in places.area.all %}
{{ place.name }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31719 次 |
| 最近记录: |