【发布时间】:2009-11-06 00:57:27
【问题描述】:
有没有办法从 Django 模板的一对多模型列表中指定一个值?
例如,我可以在 shell 中执行此操作:author.book_set.get(publisher=my_publisher)。但是我想要在我的模板中使用类似的东西。我只是将作者、作者和出版商列表传递给模板。
型号:
class Publisher(models.Model):
name = models.CharField(max_length=30)
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField(blank=True, null=True)
num_pages = models.IntegerField(blank=True, null=True)
模板:
{% for author in authors %}
{{ author.book_set.get(publisher=publisher) }}<br/> {% comment %} this is the part that needs to be corrected {% endcomment %}
{% endfor %}
【问题讨论】: