Python ManyToManyField关系检索不到数据
我有一个这样的结构: 1.作者 2.书 3.作者类型 4.AuthorBookType 一本书可以有多个作者,书中可以有“作者”、“合著者”、“部分”、“助手”等功能: 我的数据库应如下所示:Python ManyToManyField关系检索不到数据,python,django,django-models,Python,Django,Django Models,我有一个这样的结构: 1.作者 2.书 3.作者类型 4.AuthorBookType 一本书可以有多个作者,书中可以有“作者”、“合著者”、“部分”、“助手”等功能: 我的数据库应如下所示: AUTHOR: __________________________ | ID | NAME | |========================| | 1 | Jhon Doe. | | 2 | Charles Albert | | 3 | Mat
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}}
{{author.books}}
{%endfor%}
回报是:
<author name>
<core.Books.None>
也许是更清晰的解决方案
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()
这里Django版本之间的语法没有区别;您找到的任何文档都仍然有效
您需要迭代多对多关系:
{% for author in authors %}
{{ author.name }}<br>
{% for book in author.books.all %}{{ book.title }}{% endfor %}
{% endfor %}
{作者中的作者%}
{{author.name}}
{%for author.books.all%}{{book.title}{%endfor%}
{%endfor%}
{% for author in authors %}
{{ author.name }}<br>
{% for book in author.books.all %}{{ book.title }}{% endfor %}
{% endfor %}