【问题标题】:How to Access Many to many field in class based views in Django?如何在 Django 中访问基于类的视图中的多对多字段?
【发布时间】:2016-12-25 00:58:00
【问题描述】:

我有两个模型,models.py 中的作者和书籍

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age = models.IntegerField()

def __str__(self):
    return '%s %s' %(self.first_name, self.last_name)

def __unicode__(self):
    return '%s %s' %(self.first_name, self.last_name)



class Book(models.Model):
    title = models.CharField(max_length=100) #name = title
    pages = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    rating = models.FloatField()
    author = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

def __str__(self):
    return self.title

def __unicode__(self):
    return self.title

现在我正在使用 ListView 列出所有书籍。在点击一本书时,我会使用以下方法获取该书的信息

class BookDetailView(generic.DetailView):
    template_name = 'books/book_detail1.html'
    model = Book
    context_object_name = 'book_detail' 

我可以访问标题、页面、价格、评级、出版商和出版日期,但无法获得所有作者(作者列表)。虽然我将简单地打印它,但它在模板中打印 None 。我什至尝试使用 For Loop 进行迭代,但没有在模板中完成

views.py

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<ul>
    <li>Price:{{ book_detail.price }}</li>  
    <li>Pub Date:{{ book_detail.publication_date }}</li>
    <li>Title: {{ book_detail.title }}</li>
    <li>Pages: {{ book_detail.pages }}</li> 
    <li>Rating: {{ book_detail.rating }}</li>
    <li>Publisher: {{ book_detail.publisher }}</li>
    <li>Author: {{ book_detail.author }}</li>   
</ul>

</body>
</html>

谁能帮我解决这个问题?

【问题讨论】:

  • 需要更多信息,您如何尝试从模板访问作者?您应该循环通过 {{ book.author.all }} 或类似的东西。
  • 向我们展示模板代码...
  • @solarissmoke 已编辑

标签: python django many-to-many django-class-based-views


【解决方案1】:

您在BookAuthor 之间定义了多对多关系,这意味着一本书可以有任意数量的作者。为了显示它们,您需要遍历作者集:

Authors:
<ul>
{% for author in book_detail.author.all %}
    <li>{{ author }}</li>
{% endfor %}
</ul>

您可能希望将该字段的名称更改为 authors 以减少混淆。

或者,如果您希望一本书只有一个作者,那么您需要使用ForeignKey 而不是ManyToManyField。在这种情况下,您现有的模板逻辑将起作用。

【讨论】:

    【解决方案2】:

    或者如果你使用基于函数的视图,定义这个视图:

    #views.py
    def book_detail_view(request, id):
        book = get_object_or_404(Book, id=id)
        authors_of_book = book.questions.all()
        template = 'books/book_detail1.html'
        context = {'authors_of_book': authors_of_book}
        return render(request, template, context)
    

    在你的模板中:

    #html.py
    <ul>
    {% for author in authors_of_book %}
        <li>{{ author }}</li>
    {% endfor %}
    </ul>
    

    更多详情请阅读this文档。

    【讨论】:

    • 问题明确提到使用基于类的视图。
    猜你喜欢
    • 2021-06-28
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 2021-05-03
    • 2012-06-29
    • 1970-01-01
    相关资源
    最近更新 更多