Django:在模板中显示ManyToManyField?

时间:2010-11-24 18:41:21

标签: django

我的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')

如何在模板中显示地方的地区名称?目前我有:

{% for place in places %}
    Name: {{ place.name }}, Area: {{ place.area}}
{% endfor %}

给出:

Area: <django.db.models.fields.related.ManyRelatedManager object at 0x10435a3d0>

{{ place.area}}只是空白。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:65)

在模板中使用 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 places.area.all %}{{ area }}<br/>{% endfor %}
{% endfor %}

答案 1 :(得分:5)

您可以使用现有的加入模板标记。

https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#join

这是代码

{% for place in places %}
    Name: {{ place.name }}, Area: {{ place.area.all|join:", " }}
{% endfor %}

答案 2 :(得分:2)

您的观看代码是什么样的?
以下是返回相关模型的一种方法:

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

这个例子仅用于说明;你想要包含错误处理代码 您的模板可能如下所示:

<h3>{{ place }}</h3>

{% if areas %}
  <ul>
  {% for area in areas %}
    <li>{{ area.name }}</li>
  {% endfor %}
  </ul>
{% endif %}