2016-08-28 4 views
0

Wie kann ich Objekte aus dem Feld ManyToMany zurückgeben? oder Wie kann ich auf Autoren zugreifen, die mit Book in Verbindung stehen ?. Danke im Voraus. Mein models.py istManyToMany-Feld zurückgeben

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

Was machen Sie? Du meinst genau? Sie müssen die Autoren aus dem Buch oder die Bücher vom Autor bekommen? – noteness

+0

Kann ich beide Wege kennen? – Harsha

Antwort

1

Sie die Book von Author durch Zugriff auf die book_set bekommen kann:

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 

Ebenso können Sie die Autoren erhalten, indem die author Variable Book Zugriff:

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

usw.

+0

Vielen Dank :) – Harsha