如何在django REST中序列化模型

时间:2015-10-16 23:03:31

标签: python django django-rest-framework

我有django模型

class User(models.Model):
    def serialize(self):
        serializer = UserSerializer(data=self)
        if serializer.is_valid():

           return serializer.data

基本上我想获得当前模型实例的序列化版本

obj = User.objects.get(pk=1)
obj.serialize()

but i get error that serializers expects Dict u gave User

1 个答案:

答案 0 :(得分:1)

不要传递data param,在这种情况下,你只需传递对象:

def serialize(self):
    serializer = UserSerializer(self)
    if serializer.is_valid():

       return serializer.data

正如您在Serializing Objects section

中看到的那样