有没有办法在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 %}
答案 0 :(得分:2)
我不确定是否可以在模板中完成。您可以在视图中为作者添加额外的属性,如下所示:
for author in authors:
author.relevant_books = author.book_set.get(publisher=publisher)