【问题标题】:Is there a way to specify a value from a list of one-to-many models at Django's Template?有没有办法从 Django 模板的一对多模型列表中指定一个值?
【发布时间】: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 %}

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    我不确定是否可以在模板中完成。您可以在视图中为作者添加一个额外的属性,如下所示:

    for author in authors:
        author.relevant_books = author.book_set.get(publisher=publisher)
    

    【讨论】:

      猜你喜欢
      • 2022-06-17
      • 2014-09-02
      • 1970-01-01
      • 2021-05-28
      • 2020-10-18
      • 2014-05-20
      • 2011-03-27
      • 2012-04-24
      • 1970-01-01
      相关资源
      最近更新 更多