首页 文章

ManyToManyField关系检索没有数据

提问于
浏览
1

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

  • 2

    这里的Django版本的语法没有区别;您找到的任何文档仍然有效 .

    您需要遍历多对多关系:

    {% for author in authors %}
        {{ author.name }}<br>
        {% for book in author.books.all %}{{ book.title }}{% endfor %}
    {% endfor %}
    
  • 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()
    

相关问题