繁体   English   中英

如何从模型中将相关数据嵌入Django?

[英]How to embed related data in Django from models?

从几天开始,我一直在研究Django。 我知道如何在Laravel中获得想要的东西,但我需要Django中的帮助。

假设我有两个表。 作者和书籍

图书表包含:

id, name, author

作者表包含:

id, name

使用Laravel,我只需添加一个提供书与作者之间关系的函数,并且Book::with('authors')将为我提供书的所有数据,以及包含该书作者详细信息的额外领域author 我不知道如何使用Django进行此快速加载。

如果假设我使用Book.objects.all()

然后,我希望将所有书籍排列在一起。 并且在每本书中,都应该有一个对象可以提供有关该作者的详细信息。 例如:

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM