ManyToManyField关系未检索任何数据

时间:2018-12-09 00:44:49

标签: python django django-models

我有一个这样的结构:  1.作者  2.书  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 %}

返回是:

<author name>
<core.Books.None>

我有什么问题吗? 我搜索了这样的示例,但是我发现了Django 1.x的一些旧示例,而2.x则没有。

在文档中,我没有找到这样的示例(仅没有联结表)。 https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/

2 个答案:

答案 0 :(得分:2)

此处Django版本之间的语法没有区别;您发现的任何文档仍然可以使用。

您需要遍历多对多关系:

{% for author in authors %}
    {{ author.name }}<br>
    {% for book in author.books.all %}{{ book.title }}{% endfor %}
{% endfor %}

答案 1 :(得分:0)

也许是更清晰的解决方案。

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()