Python django序列化器 - > validated_data删除字段

时间:2017-06-10 11:00:12

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

目标:将对象添加到另一个DataModel的ManyToMany字段。

包含ManyToMany字段的数据模型:

class ObservedDataModel(models.Model):
    domain_objects = models.ManyToManyField(DomainNameModel, blank=True)

以下代码有效,但外来对象id是硬编码的((ObservedDataModel, id=2)):

class DomainSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = DomainNameModel
        fields = ('url', 'id', 'name')

    def create(self, validated_data):
        domain_obj = DomainNameModel.objects.create(name=validated_data['name'])

        observed_data_object = get_object_or_404(ObservedDataModel, id=2)  # TODO !!!!!!
        observed_data_object.domain_objects.add(domain_obj)

        return domain_obj

要让用户设置(ObservedDataModel, id=X)我尝试发送请求{'name': 'apple.com', 'observeddata': 2},但validated_data字段不包含变量observeddata

那么如何在validated_data变量中添加自定义(非模式)字段?

2 个答案:

答案 0 :(得分:2)

刚刚使用stackoverflow建议找到了我的问题的答案(很棒的功能!)。解决方案是覆盖to_internal_value,如下所示:

def to_internal_value(self, data):
    internal_value = super(DomainSerializer, self).to_internal_value(data)
    my_non_model_field_raw_value = data.get("observeddata")
    my_non_model_field_value = my_non_model_field_raw_value
    internal_value.update({
        "observeddata": my_non_model_field_value
    })
    return internal_value

Thanks to trubliphone

答案 1 :(得分:0)

重写序列化程序的init方法,

class DomainSerializer(serializers.HyperlinkedModelSerializer): 

    def __init__(self, obs_data, *args, **kwargs):
        super(DomainSerializer, self).__init__(*args, **kwargs)
        self.obs_data = obs_data

    class Meta: 
        model = DomainNameModel
        fields = ('url', 'id', 'name') 

    def create(self, validated_data):
        domain_obj = DomainNameModel.objects.create(name=validated_data['name'])
        observed_data_object = get_object_or_404(ObservedDataModel, id=self.obs_data) # here's the item....
        observed_data_object.domain_objects.add(domain_obj)
        return domain_obj

在视图中,

DomainSerializer(data=your_data, obs_data=observed_data_id)