2017-12-10 23 views
0

私は数日からDjangoに取り組んできました。私はLaravelで私が望むものを得る方法を知っていますが、私はDjangoで助けが必要です。Djangoに関連するデータをモデルから埋め込む方法は?

私は2つのテーブルがあるとします。 著者や書籍

ブックテーブルが含まれています

id, name, author 

authorsテーブルが含まれています

Laravelで
id, name 

、私はちょうど与えるの書籍や著者とBook::with('authors')との間の関係を与える関数を追加することができます私は本のすべてのデータと一緒に本の著者の詳細を含む余分なフィールドauthorを持っています。私はDjangoでこのEager Loadingを行う方法を知らない。

私はその後、私は、アレイ内のすべての書籍を望む Book.objects.all()

を使用すると仮定した場合。本の各項目には、その著者についての詳細を示す1つのオブジェクトが用意されていなければなりません。 例えば:

{ 
[ 
{ 
id: 3 
name: "Name of book", 
author: { 
    id: 7, 
    name: "Author name" 
} 
}, 
{ 
id: 4 
name: "Name of other book", 
author: { 
    id: 3, 
    name: "Author of other book" 
} 
} 
] 
} 

答えて

0
class Base(models.Model): 
    name = models.Charfield(max_length=100) 

    def to_dict(self): 
     rtn = {} 
     c = self._meta._get_fields(reverse=False) 
     for i in c: 
      item = str(i).split('.')[2] 
      if hasattr(self, item): 
       rtn[item] = getattr(self, item) 
     return rtn 

class Books(Base): 
    author = models.ForeignKey(Author, related_name='authors') 

    @classmethod 
    def get_all_books(cls): 
     l = [] 
     books = cls.objects.all() 
     for book in books: 
      book_dict = book.to_dict() 
      book_dict['author'] = book.author.to_dict() 
      l.append(book_dict) 

     return {'result': l} 

class Author(Base): 

    def __str__(self): 
     return self.name 

私はあなたがしなければならないすべてはちょうど

Book.get_all_books() 

を呼び出している結果がこの

{ 
'result': [ 
    { 
    id: 3 
    name: "Name of book", 
    author: { 
     id: 7, 
     name: "Author name" 
    } 
    }, 
    { 
    id: 4 
    name: "Name of other book", 
    author: { 
     id: 3, 
     name: "Author of other book" 
    } 
    } 
] 

}のようになり、このようにYの答えを編集しました

+0

申し訳ありませんが、あなたは何かを理解しているようです他にもあります。私はその質問にさらに詳しい説明を追加しました。 –

+0

私は答えを編集しました... –

関連する問題