Django超级函数不会向类添加变量

时间:2015-10-11 10:29:32

标签: python django django-rest-framework django-serializer

我正在尝试使用 init 在MozSerializer类中创建新变量,以获取从另一个函数传递的数据。这是代码:

class MozSerializer(serializers.Serializer):

    def __init__(self, modelid, data=None):        
        self.modelid = modelid        
        super(MozSerializer, self).__init__(modelid=self.modelid)

    keyword = serializers.PrimaryKeyRelatedField(queryset=modelid.objects.all())
    pda = serializers.FloatField()
    upa = serializers.FloatField()

我的目标是将此'modelid'从另一个函数传递给序列化程序(第7行... queryset = MODELID ...)。

1 个答案:

答案 0 :(得分:1)

执行此操作的正确方法是在__init__中添加字段dynamically

class MozSerializer(serializers.Serializer):

    def __init__(self, *args, **kwargs):        
        modelid = kwargs.pop('modelid')
        self.fields['keyword'] = serializers.PrimaryKeyRelatedField(\
                                             queryset=modelid.objects.all())       
        super(MozSerializer, self).__init__(*args, **kwargs)

    pda = serializers.FloatField()
    upa = serializers.FloatField()