简体   繁体   English

如何修改 django rest 框架发送的响应

[英]How can modify response send by django rest framework

I am using Django REST as backend and angular as front end.我使用Django REST as backend和 angular 作为前端。

I have two serializers one for readong GET requests and other for POST, PUT requests.我有两个序列化程序,一个用于 readong GET 请求,另一个用于 POST、PUT 请求。

This was because there are few fields like interval , etc which i am entering in integer by user but in the database i am saving as timedelta so i have to multitply them to make them as seconds on front end.这是因为我在interval中输入的字段很少,例如用户,但在数据库中我保存为 timedelta,所以我必须将它们相乘以使它们成为前端的秒数。

so eg interval = 5 entered by user and i am posting 5*60*60 to server.因此,例如用户输入的interval = 5 ,我将5*60*60发布到服务器。

In order to read i have made ReadSerializer where i am diving that by 60*60 to again show to user what he added.为了阅读,我制作了ReadSerializer ,我将其潜水 60*60 以再次向用户显示他添加的内容。

This is working find my problem is after saving my object to database the djnago rest frameework sends the object as it is saved which has interval = 5*60*60 .这是工作发现我的问题是在将我的 object 保存到数据库后 djnago rest 框架发送 object 因为它被保存为 06,其interval = 5*60*60 inerval is just an example there 4-5 felds where i am changing them in front end before posting inerval 只是一个例子,有 4-5 个字段,我在发布之前在前端更改它们

Is there any way that response used my READ serializer before sending有没有什么方法可以让响应READ serializer before sending程序

class Serializer(serializers.ModelSerializer):
    interval = serializers.SerializerMethodField('get_interval')

    class Meta:
        model = User
        fields = ('id', 'interval')

    def get_interval(self, obj):
        return obj.interval/60*60

class WriteSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'interval')

This is the view这是视图

class UserListCreateView(generics.ListCreateAPIView):
    queryset = User.objects.filter(is_deleted=False)

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return ReadSerializer
        return WriteSerializer

You can use the transform_field method which allows you to customize the representation of a field when showing it. 您可以使用transform_field方法,该方法允许您在显示字段时自定义字段的表示形式。

Documentation about it: http://www.django-rest-framework.org/api-guide/serializers/#customizing-field-representation 有关它的文档: http//www.django-rest-framework.org/api-guide/serializers/#customizing-field-representation

Btw, careful if you are planning to upgrade to new versions of drf (>=3), these methods may disappear in favour of a unique to_representation method: https://groups.google.com/forum/?fromgroups#!topic/django-rest-framework/9kp5kXCssR4 顺便说一下,如果你打算升级到drf(> = 3)的新版本,请注意这些方法可能会消失,转而采用独特的to_representation方法: httpsto_representation to_representationtopic / Django的休息框架/ 9kp5kXCssR4

I would just change it in JavaScript on the front end.我只是在前端的 JavaScript 中更改它。 However I have a similar issue and solved it like this, (warning, I just started using DRF, so may not be the best way):但是我有一个类似的问题并像这样解决了它,(警告,我刚开始使用 DRF,所以可能不是最好的方法):

Just change the response of the method directly by first getting the original response, then editing the data property of it, which is a dict (pre-serialized) of the data to return:只需直接更改方法的响应,首先获取原始响应,然后编辑它的data属性,这是要返回的数据的 dict(预序列化):

class UserListCreateView(generics.ListCreateAPIView):
    ...

    def list(self, request, *args, **kwargs):
            response = super().list(request, *args, **kwargs)
            response.data['interval'] = response.data['interval'] / 60 / 60
            return response

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM