Django Rest - 在get _ ***方法中包含序列化程序对象

时间:2015-06-29 20:00:21

标签: python django serialization django-models django-rest-framework

我正在尝试将相关模型的序列化对象包含在另一个序列化程序的自定义对象中,但我无法弄清楚如何执行此操作。

我有两个模型 - 片段和用户。代码段模型具有用户的外键。我需要的是在" get_included"中包含片段的序列化对象。 UserSerializer的方法,并让UserSerializer返回一个像这样的JSON对象:

{
   "id" : 1,
   "included": [
      {'id': 2,'created': "20150729" },
      {'id': 3,'created': "20150730" }, 
   ]
}

以下是我的代码。

# Snippet Model
from django.db import models
class Snippet(models.Model):
   created = models.DateTimeField(auto_now_add=True)
   user = models.ForeignKey('auth.User', related_name='snippets')

# Snippet serializer
class SnippetSerializer(serializers.ModelSerializer):
   model = Snippet
   fields = ('id','created')

# User serializer
from .serializers import SnippetSerializer
class UserSerializer(serializers.ModelSerializer):
  included = serializers.SerilizerMethodField()
  class Meta: 
     model = User
     depth = 1 
     fields = ('id','included')

  def get_included(self, obj):
     snippets = SnippetSerializer(many=True, read_only=True).data

     return snippets

1 个答案:

答案 0 :(得分:1)

不需要get_included方法。只需将snippets属性添加到类中即可。

class UserSerializer(serializers.ModelSerializer):
    included = SnippetSerializer(many=True, read_only=True)

    class Meta: 
        model = User
        depth = 1 
        fields = ('id','included')