Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

Django: show a ManyToManyField in a template?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 place.area.all %}{{ area }}<br/>{% endfor %}
{% endfor %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...