Django rest框架在序列化器中添加字段,仅用于post方法

时间:2014-01-13 18:06:29

标签: django django-rest-framework

我正在尝试使用HyperlinkedModelSerializer构建一个序列化程序,但我有一个场景,我想添加一个模型中不存在的字段,但我需要验证事务的值,我找到了下面的代码片段

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework import serializers
import logging

# initiate logger
logging.getLogger(__name__)


class PostHyperlinkedModelSerializerOptions(serializers.HyperlinkedModelSerializerOptions):
    """
   Options for PostHyperlinkedModelSerializer
   """

    def __init__(self, meta):
        super(PostHyperlinkedModelSerializerOptions, self).__init__(meta)
        self.postonly_fields = getattr(meta, 'postonly_fields', ())


class PostHyperlinkedModelSerializer(serializers.HyperlinkedModelSerializer):
    _options_class = PostHyperlinkedModelSerializerOptions

    def to_native(self, obj):
        """
       Serialize objects -> primitives.
       """
        ret = self._dict_class()
        ret.fields = {}

        for field_name, field in self.fields.items():
            # Ignore all postonly_fields fron serialization
            if field_name in self.opts.postonly_fields:
                continue
            field.initialize(parent=self, field_name=field_name)
            key = self.get_field_key(field_name)
            value = field.field_to_native(obj, field_name)
            ret[key] = value
            ret.fields[key] = field
        return ret

    def restore_object(self, attrs, instance=None):
        model_attrs, post_attrs = {}, {}
        for attr, value in attrs.iteritems():
            if attr in self.opts.postonly_fields:
                post_attrs[attr] = value
            else:
                model_attrs[attr] = value
        obj = super(PostHyperlinkedModelSerializer,
                    self).restore_object(model_attrs, instance)
        # Method to process ignored postonly_fields
        self.process_postonly_fields(obj, post_attrs)
        return obj

    def process_postonly_fields(self, obj, post_attrs):
        """
       Placeholder method for processing data sent in POST.
       """
        pass

class PurchaseSerializer(PostHyperlinkedModelSerializer):
    """ PurchaseSerializer
    """
    currency = serializers.Field(source='currency_used')

    class Meta:
        model = DiwanyaProduct
        postonly_fields = ['currency', ]

使用上面的类PostHyperlinkedModelSerializer,但由于某种原因,上面的问题导致了休息框架的可浏览api接口问题。字段标签正在消失,加上新字段“货币”未在表单中显示(请参阅下面的屏幕截图以供参考)。任何人都可以提供帮助吗?

enter image description here

1 个答案:

答案 0 :(得分:2)

编写代码的人可能不需要浏览api(正常请求可以正常工作)。

为了修复api更改to_native

def to_native(self, obj):
    """
    Serialize objects -> primitives.
    """
    ret = self._dict_class()
    ret.fields = self._dict_class()

    for field_name, field in self.fields.items():

        if field.read_only and obj is None:
            continue

        field.initialize(parent=self, field_name=field_name)
        key = self.get_field_key(field_name)
        value = field.field_to_native(obj, field_name)

        method = getattr(self, 'transform_%s' % field_name, None)
        if callable(method):
            value = method(obj, value)

        if field_name not in self.opts.postonly_fields:
            ret[key] = value

        ret.fields[key] = self.augment_field(field, field_name, key, value)
    return ret