gpt4 book ai didi

Django:在模板中显示 ManyToManyField?

转载 作者:行者123 更新时间:2023-11-28 19:35:56 25 4
gpt4 key购买 nike

我的 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}} 只是空白。谁能帮忙?

最佳答案

在模板中使用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 %}

关于Django:在模板中显示 ManyToManyField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4270330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com