2016-08-28 107 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