返回ManyToMany字段

时间:2016-08-28 11:05:18

标签: python-2.7 django-models

如何从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

1 个答案:

答案 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