如何在Django中基于类的视图中访问多对多字段? [英] How to Access Many to many field in class based views in Django?
问题描述
我有两个模型,作者&预订models.py
I have two models, Author & Book in 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列出所有书籍.点击一本书,我就可以使用以下方法获取这本书的信息
Now i'm listing all the books using ListView. And on click of a book i'm getting information the book using following method
class BookDetailView(generic.DetailView):
template_name = 'books/book_detail1.html'
model = Book
context_object_name = 'book_detail'
我可以访问标题,页面,价格,评分,发布商和publication_date,但未获取所有作者(作者列表).虽然我将只打印它,但它在模板中不打印任何内容.我什至尝试使用For Loop进行迭代,但未在模板中完成
I'm able to access title, pages, price, rating, publisher & publication_date but not getting all the Authors(Author list). While i'm going to simply print it, it prints None in template. I even try to iterate using For Loop but not done in template
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>
有人可以帮助我摆脱困境吗?
Can anyone help me to out from this?
推荐答案
您已定义Book
和Author
之间的多对多关系,这意味着一本书可以有任意数量的作者.为了显示它们,您需要遍历所有作者:
You have defined a many-to-many relationship between Book
and Author
which means that a book can have any number of authors. In order to display them you need to loop through the set of authors:
Authors:
<ul>
{% for author in book_detail.author.all %}
<li>{{ author }}</li>
{% endfor %}
</ul>
您可能希望将该字段的名称更改为authors
,以减少混乱.
You might want to change the name of that field to authors
to be less confusing.
或者,如果您只想为一本书作者,那么您需要使用ForeignKey
而不是ManyToManyField
.在这种情况下,您现有的模板逻辑将起作用.
Alternatively if you want only one author for a book then you need to use a ForeignKey
instead of a ManyToManyField
. In that case your existing template logic would work.
这篇关于如何在Django中基于类的视图中访问多对多字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!