我有一个这样的结构: 1. Author 2. Book 3. AuthorType 4. AuthorBookType一本书可以有多个作者,并且它可以在书中具有以下功能:“作者”、“共同作者”、“部分”、“助手”等:class Book(models.Model): title=models.CharField(max_length=100)class Author(models.Model): name=models.CharField(max_length=100) books=models.ManyToManyField(Book, through='AuthorBookType')class AuthorType(models.Model): description=models.CharField(max_length=100)class AuthorBookType(models.Model): author=models.ForeignKey(Author, on_delete=models.CASCADE) book=models.ForeignKey(Book, on_delete=models.CASCADE) author_type=models.ForeignKey(AuthorType, on_delete=models.CASCADE)我的数据库应该是这样的:AUTHOR:__________________________| ID | NAME ||========================|| 1 | Jhon Doe. || 2 | Charles Albert || 3 | Matt Greg || 4 | Anne Engel |--------------------------BOOK:__________________________| ID | NAME ||========================|| 1 | Paradise City || 2 | Profaned Apple |--------------------------AUTHOR_TYPE:__________________________| ID | DESCRIPTION ||========================|| 1 | Author || 2 | Co-Author |--------------------------AUTHOR_BOOK_TYPE:_____________________________________________| ID | AUTHOR_ID | BOOK_ID | AUTHOR_TYPE_ID ||===========================================|| 1 | 1 | 1 | 1 || 2 | 2 | 1 | 2 || 3 | 3 | 1 | 2 || 4 | 3 | 2 | 1 || 5 | 4 | 2 | 2 |---------------------------------------------在我的 views.py 上我做了:class AuthorsListView(ListView) model = Author context_object_name = 'authors' template_name = 'core/authors_list.html'然后在我的模板上:{% for author in authors %} {{ author.name }}<br> {{ author.books }}{% endfor %}在文档中我没有发现这样的例子(只有没有连接表)。 https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/
2 回答

摇曳的蔷薇
TA贡献1793条经验 获得超6个赞
也许更清晰的解决方案。
from .models import Author
class AuthorsListView(ListView)
model = Author
context_object_name = 'authors'
template_name = 'core/authors_list.html'
def get_queryset(self):
return Author.objects.all()
添加回答
举报
0/150
提交
取消