一尘不染

Django:在模板中显示ManyToManyField吗?

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}}只是空白。有人可以帮忙吗?


阅读 497

收藏
2020-03-31

共1个答案

一尘不染

{% for place in places %}
    Name: {{ place.name }}<br/>
    Area: <br/>{% for area in place.area.all %}{{ area }}<br/>{% endfor %}
{% endfor %}
2020-03-31