无法在 Django 中获取关系属性,多对多关系
Unable to get relation attribute in Django, many-to-many relationship
models.py:
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ManyToManyField(Author)
def __str__(self):
return self.title
我可以通过 author
关系过滤 books
:
>>> Book.objects.filter(author__name__contains="Fyodor")
<QuerySet [<Book: Crime and Punishment>, <Book: The Brothers Karamazov>]>
但是,我无法获得 本书的作者:
>>> all_books = Book.objects.all()
>>> all_books[0].author
<django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7fdf068a2b20>
>>> all_books[0].author.name
>>>
有什么建议吗?
书籍和作者之间存在 ManyToMany
关系,因此每本书都会有很多作者。因此 book.author
给你一个作者查询集。
因此你需要做这样的事情:
# get a single book:
book = Book.objects.get(id=<the-book-id>)
# get all the authors of a book:
authors = book.author.all()
# get the first author of the book:
first_author = authors.first()
name = first_author.name
models.py:
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ManyToManyField(Author)
def __str__(self):
return self.title
我可以通过 author
关系过滤 books
:
>>> Book.objects.filter(author__name__contains="Fyodor")
<QuerySet [<Book: Crime and Punishment>, <Book: The Brothers Karamazov>]>
但是,我无法获得 本书的作者:
>>> all_books = Book.objects.all()
>>> all_books[0].author
<django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7fdf068a2b20>
>>> all_books[0].author.name
>>>
有什么建议吗?
书籍和作者之间存在 ManyToMany
关系,因此每本书都会有很多作者。因此 book.author
给你一个作者查询集。
因此你需要做这样的事情:
# get a single book:
book = Book.objects.get(id=<the-book-id>)
# get all the authors of a book:
authors = book.author.all()
# get the first author of the book:
first_author = authors.first()
name = first_author.name