Django:序列化查询集并包含一对多关系子项

Adr*_*ler 3 django serialization django-queryset

我想序列化一个对象的查询集,该对象与另一个模型有一对多的关系.我想在json输出中包含相关对象.

例:

class Book(models.Model):
    title = models.CharField()
    author = models.ForeignKey('Author')

class Author(models.Model):
    name = models.CharField()

view.py:

serializers.serialize('json', Author.objects.all()) #does not include the book objects
Run Code Online (Sandbox Code Playgroud)

我很确定有一个简单的解决方案,但到目前为止我无法弄清楚如何做到这一点.谢谢你的帮助!

sne*_*awo 6

您无法从默认的django序列化程序中执行此操作,因为Author模型没有books字段.您可以通过创建自己的序列化程序或手动构建数据并将其传递给simplejson.dumps()来实现它.

更新

例如:

class Author(models.Model):
    ...
    def get_json(self):
        return {
            'id': self.id, 
            'name': self.name,
            'books': [{'id': b.id, 'title': b.title} for b in self.book_set.all()] }

from django.utils import simplejson
simplejson.dumps([a.get_json() for a in Author.objects.all()])
Run Code Online (Sandbox Code Playgroud)