我的模型是这样设计的:
class Author(models.Model):
author_name = models.Charfield(max_length = 15)
class Books(models.Model):
book_name = models.CharField(max_length = 15)
authors = models.ManytoManyField(Author)
存储在authors字段中的数据如下:
authors Author A
Author A
Author B
Author B
Author C
现在,在我的views.py文件中,我正试图查询这样的数据:
allAuthors = Books.objects.all()
for a in allAuthors:
print(a.authors)
显示的输出为:
Author A
Author B
Author C
为什么不显示重复项?如何同时显示重复项?很抱歉我错过了显而易见的东西。感谢您提前抽出时间。
试试这个
all_books = Books.objects.all()
for book in all_books:
authors = book.authors.all()
if authors:
for author in authors:
print(author.author_name)