2016-08-28 74 views
0

如何从ManyToMany字段返回对象?或者我如何访问与Book有关的作者?提前致谢。我的models.py是返回ManyToMany字段

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

什么哟你的意思是?你需要从书中得到作者还是作者的书? – noteness

+0

我可以同时知道吗? – Harsha

回答

1

您可以通过访问book_setAuthor得到Book

Book.get(title="A book").author.all() 

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 

同样,你可以通过访问Bookauthor变量得到作者

+0

非常感谢你:) – Harsha