如何从ManyToMany字段返回对象?或者如何访问与Book相关的作者?提前致谢。我的models.py是
class Author(models.Model):
first_Name = models.CharField(max_length=100)
last_Name = models.CharField(max_length=100)
def __unicode__(self):
return 'Author: ' + self.first_Name + ' ' + self.last_Name
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ManyToManyField('Author')
def __unicode__(self):
return 'Book: ' + self.title
答案 0 :(得分:1)
您可以访问Book
来获取Author
的{{1}}:
book_set
同样,您可以通过访问Author.get(first_Name="Someone").book_set.all() # would return a list of all books
Author.get(first_Name="Someone").book_set.get(...) # would a book
的{{1}}变量来获取作者:
author
等