在Django-template中反向M2M查询

时间:2017-07-07 09:54:12

标签: python django django-templates django-views

我想在模板中获取发言人的姓名。我用xxxx标记了它。我怎样才能做到这一点?非常感谢您的帮助。我的档案:

models.py

class City(models.Model):
    name = models.CharField(max_length=100)

class Speaker(models.Model):
    name = models.CharField(max_length=100)
    url = models.URLField(max_length=100)
    city = models.ManyToManyField(City, blank=True)

views.py

def home(request):
    cities = City.objects.all().exclude(speaker__isnull=True)
    return render(request, "index.html", {"cities":cities})

的index.html

{% for i in cities %}
{{ i.name }},xxx{{ i.speaker.name }}xxx<br>
{% endfor %}

1 个答案:

答案 0 :(得分:0)

您可以speaker_set

访问每个城市的发言人
{% for cit in cities %}
   {{ cit.name }}
   {% for spkr in cit.speaker_set.all %}
      {{ spkr.name }}
   <br>
   {% endfor %}
{% endfor %}