python - Django 序列化器 : why does self. fields.pop ('field_name' )工作吗?

标签 python django python-2.7 django-serializer

引用以下链接作为示例(其他地方也存在大量其他示例): http://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields

据了解,Django 序列化器字段通常使用元组定义,该元组是不可变的:

class UserSerializer(DynamicFieldsModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email')

但是,动态更改序列化器字段的可接受方法涉及使用 pop (self.fields.pop(field_name))

class DynamicFieldsModelSerializer(serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):
        # Don't pass the 'fields' arg up to the superclass
        fields = kwargs.pop('fields', None)

        # Instantiate the superclass normally
        super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)

        if fields is not None:
            # Drop any fields that are not specified in the `fields` argument.
            allowed = set(fields)
            existing = set(self.fields)
            for field_name in existing - allowed:
                self.fields.pop(field_name)

字段如何定义? Django 序列化程序中有预处理步骤吗?

最佳答案

看:

https://github.com/encode/django-rest-framework/blob/3fcc076d9124fc202be1a4379b6b753209c7afbe/rest_framework/serializers.py#L354

def fields(self):
    """
    A dictionary of {field_name: field_instance}.
    """
    # `fields` is evaluated lazily. We do this to ensure that we don't
    # have issues importing modules that use ModelSerializers as fields,
    # even if Django's app-loading stage has not yet run.
    if not hasattr(self, '_fields'):
        self._fields = BindingDict(self)
        for key, value in self.get_fields().items():
            self._fields[key] = value
    return self._fields

How do fields get defined?

现在应该很清楚了。

Is there a pre-processing step in Django serializers?

是的。 这个“步骤”叫做metaclass

SerializerModelForms都是元类。

关于python - Django 序列化器 : why does self. fields.pop ('field_name' )工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50848182/

相关文章:

python - 如何在 peewee 元类中使用默认排序

django - 如何覆盖 wagtail 身份验证?

django - 使用 docker compose,如何使用相同的地址在内部和外部访问服务?

python-2.7 - 在 tkinter 窗口中嵌入 pyplot 并更新它

python - 在Python 2.7中,我们可以从子类的类方法中调用父类的实例方法吗?

python - 从 Bigquery 中读取几行作为辅助输入,得到 None

python - 索引在python中是什么意思?

python - 套接字编程;通过多个设备传输时文件损坏

python - pygtk 从父节点按名称获取小部件

python - 如何使syncdb显示完整的堆栈跟踪