简体   繁体   English

SerializerMethodField 的 DRF Serializer 访问值

[英]DRF Serializer access value of SerializerMethodField

class SimpleSerializer(serializers.HyperlinkedModelSerializer):
    value_x = serializers.SerializerMethodField('func_x')
    value_y = serializers.SerializerMethodField('func_y')

    def func_x(self, obj):
        return 0 

    def func_y(self, obj):
        value_x ?? 

In above's example is there any way to access the variable value_x within func_y whereas value_x should have the value of 0?在上面的示例中,有什么方法可以访问func_y中的变量value_xvalue_x的值应该为 0?

I've tried accessing it by just value_x and self.value_x but obviously both don't work我试过只通过value_xself.value_x访问它,但显然两者都不起作用

There's a hint in this question and its associated answers. 这个问题及其相关答案中有一个提示。

In your serializer you can access the other fields by using self.get_<field_name> as described in the DRF documentation , ie in your case (you're overriding the method names so be aware of that) it should work like this:在您的序列化程序中,您可以使用self.get_<field_name>访问其他字段,如DRF 文档中所述,即在您的情况下(您正在覆盖方法名称,因此请注意),它应该像这样工作:

class SimpleSerializer(serializers.HyperlinkedModelSerializer):
    value_x = serializers.SerializerMethodField('func_x')
    value_y = serializers.SerializerMethodField('func_y')

    def func_x(self, obj):
        return 0 

    def func_y(self, obj):
        return self.func_x(obj) + 1

Side note: I like to move the SerializerMethodField function to a mixin to make it reusable and enhance maintainability, so I prefer something like the below.旁注:我喜欢将SerializerMethodField函数移动到一个 mixin 中,以使其可重用并增强可维护性,所以我更喜欢下面这样的东西。

class ValueXMixin():
    def get_value_x(self, obj):
        return self.func_x(obj) + 1


class ValueYMixin():
    def get_value_y(self, obj):
        return 0

class SimpleSerializer(serializers.HyperlinkedModelSerializer, ValueXMixin, ValueYMixin):
    value_x = serializers.SerializerMethodField()
    value_y = serializers.SerializerMethodField()

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

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