ManyToManyField 关系不检索数据

我有一个这样的结构: 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/


蝴蝶刀刀
浏览 173回答 2
2回答

摇曳的蔷薇

也许更清晰的解决方案。from .models import Authorclass AuthorsListView(ListView)&nbsp; &nbsp; model = Author&nbsp; &nbsp; context_object_name = 'authors'&nbsp; &nbsp; template_name = 'core/authors_list.html'&nbsp; &nbsp; def get_queryset(self):&nbsp; &nbsp; &nbsp; &nbsp; return Author.objects.all()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python