2017-12-10 3 views
0

나는 며칠이 지난 지금 장고를 연구 해왔다. 나는 내가 원하는 것을 Laravel에서 얻는 방법을 알고 있지만 장고에서는 도움이 필요하다.Django에서 관련 데이터를 모델에서 삽입하는 방법은 무엇입니까?

두 개의 테이블이 있다고 가정합니다. 저자와 책

책 테이블이 포함되어

id, name, author 

저자 테이블이 포함되어

Laravel와
id, name 

, 난 그냥 줄 것이다 책과 저자와 Book::with('authors') 사이의 관계를 제공하는 기능을 추가 할 수 있습니다 책의 모든 데이터와 책의 저자 세부 사항이 포함 된 추가 필드 author. 장고와 함께이 Eager Loading을하는 법을 모르겠습니다.

내가 그럼 난 배열에있는 모든 책을 원하는 것이 Book.objects.all()

를 사용한다고 가정합니다. 책의 모든 항목에는 해당 저자에 대한 세부 정보를 제공 할 수있는 하나의 개체가 있어야합니다. 예를 들어 :이 방법으로 y를 대답을 편집

{ 
[ 
{ 
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" 
    } 
    } 
] 

같은 것를 호출한다}

+0

죄송합니다.하지만 이해하신 것처럼 보입니다. 다른 것. 질문에 더 많은 설명을 추가했습니다. –

+0

답변을 편집했습니다 ... –

관련 문제