简体   繁体   English

ModelSerializer 中的自定义可写字段

[英]Custom writable field in ModelSerializer

I'd like to add a custom field to a serializer that's used when creating resources.我想在创建资源时使用的序列化程序中添加一个自定义字段。 It's not a model field.这不是一个模型领域。

I tried the following:我尝试了以下方法:

class CampaignSerializer(ModelSerializer):
    class Meta:
        model = Campaign
        fields = ("groups",)
        write_only_fields = ("groups",)

    groups = ListField(IntegerField(), min_length=1)

    def validate(self, data):
        # ...
        return data

However groups doesn't exist in data in the validate() function.但是validate()函数中的data中不存在groups I found out that DRF sets read_only=True for the field, which is definitely not what I want.我发现 DRF 为该字段设置了read_only=True ,这绝对不是我想要的。

Is there a way to specify a writable field, or do I have to resort to the view set's perform_create() method?有没有办法指定一个可写字段,还是我必须求助于视图集的perform_create()方法?

The following will work, but is likely not the intended way of doing it:以下方法可行,但可能不是预期的方式:

from rest_framework import serializers


class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ('foo', )  # also add your normal model fields

    foo = serializers.SerializerMethodField()

    def get_foo(self, obj):
        return ...  # do necessary reading stuff

    def create(self, validated_data):
        # use self.initial_data to access the raw input data sent in POST request
        self.initial_data['foo']  
        ...  # do necessary validations of 'foo'
        instance = super().create(validated_data)
        ...  # do necessary write stuff
        return instance

    # Do likewise with .update method

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

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