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
我可以books按author關系過濾:
>>> 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
>>>
有什么建議?
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/400923.html
