【问题标题】:How to embed related data in Django from models?如何从模型中将相关数据嵌入到 Django 中?
【发布时间】:2018-05-24 00:32:10
【问题描述】:

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

假设我有两张桌子。 作者和书籍

books 表包含:

id, name, author

authors 表包含:

id, name

使用 Laravel,我可以添加一个函数来给出书籍和作者之间的关系,Book::with('authors') 会给我书籍的所有数据以及包含书籍作者详细信息的额外字段 author。我不知道如何使用 Django 进行这种 Eager Loading。

如果假设我使用 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"
 }
}
]
}

【问题讨论】:

    标签: python django laravel django-models eager-loading


    【解决方案1】:
    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"
        }
      }
    ]
    

    }

    【讨论】:

    • 很抱歉,但您似乎理解了其他内容。我在问题中添加了更多描述。
    猜你喜欢
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多