Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 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 Answer

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 %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...