在Django Rest框架中使用serializer定制输出 [英] Custom output with serializer in Django Rest Framework
问题描述
在创建用户对象时,我想显示自定义输出,即 success = true
。
I'd like to display custom output, i.e success=true
when a user object is created.
这是我现在可以正常工作的代码:
This is the code I have now which works fine:
class UserViewSet(viewsets.ViewSet):
queryset = User.objects.all()
def post(self, request, *args, **kwargs):
# ... do some stuff
return Response('some custom response')
我的问题是我还需要一些字段,例如用户名和密码。
My problem is that I also need to have some fields required, e.g username and password.
我假设我需要一个序列化器。在我的 ViewSet
中添加一个序列化程序,现在我有另一个问题。我不能得到它返回我的自定义输出。
I'm assuming I need a serializer for that. Adding a serializer to my ViewSet
and now I have another problem. I can't get it to return my custom output.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
def restore_object(self, attrs, instance=None):
#... do some stuff
return Response('sadf') # obviously this won't work
我试图找到覆盖该方法来控制序列化程序的输出,但是找不到它。
I'm trying to find the method to override that controls the output of the serializer but I can't find it.
推荐答案
您正在寻找的方法是to_native。
The method you are looking for is to_native.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
def to_native(self, obj):
return 'some custom response'
请注意, to_native
已重命名为 to_representation
Django Rest Framework 3.0
Note that to_native
is renamed to to_representation
in Django Rest Framework 3.0
这篇关于在Django Rest框架中使用serializer定制输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!