为了账号安全,请及时绑定邮箱和手机立即绑定

ManyToManyField 关系不检索数据

ManyToManyField 关系不检索数据

蝴蝶刀刀 2021-09-11 15:44:01
我有一个这样的结构: 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()


查看完整回答
反对 回复 2021-09-11
  • 2 回答
  • 0 关注
  • 172 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号