Skip to content

Instantly share code, notes, and snippets.

@zhu327
Last active May 27, 2017 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhu327/751bb3e9984d45565e1f0affe5baf5cf to your computer and use it in GitHub Desktop.
Save zhu327/751bb3e9984d45565e1f0affe5baf5cf to your computer and use it in GitHub Desktop.
DRF Serializer
class DynamicFieldsModelSerializer(serializers.ModelSerializer):
"""
A ModelSerializer that takes an additional `fields` argument that
controls which fields should be displayed.
"""
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.keys())
for field_name in existing - allowed:
self.fields.pop(field_name)
class CustomSerializerMixin(object):
u"""
在GenericAPIView的子类中使用的自定义序列化类Mixin,包括APIView ViewSet
serializer_class: 在自定义序列化类字典中如果没有,则选择默认的serializer_class
custom_serializer_classes: 自定义序列化类字典
custom_serializer_classes = {
"list": 列表
"create": 创建
"retrieve": 详情
"update": 更新
"destroy": 删除
}
"""
serializer_class = None
custom_serializer_classes = {}
def get_serializer_class(self):
""" Return the class to use for serializer w.r.t to the request method."""
if hasattr(self, 'action') and self.action in self.custom_serializer_classes:
return self.custom_serializer_classes[self.action]
return super(CustomSerializerMixin, self).get_serializer_class()
# http://stackoverflow.com/questions/17577177/creating-a-rest-api-for-a-django-application/37769847#37769847
from jsonschema import validate
from jsonschema.exceptions import ValidationError as JSONSchemaValidationError
from rest_framework import serializers
class JsonSchemeSerializer(serializers.BaseSerializer):
u"""
用于复杂json schema的验证, 只做反序列化, 不做序列化
"""
SCHEMA = None
def to_internal_value(self, data):
try:
validate(data, self.SCHEMA)
except JSONSchemaValidationError as e:
raise serializers.ValidationError(e.message)
return data
def schema_factory(schema):
u"""
schema serializer factory
"""
class Serializer(JsonSchemeSerializer):
SCHEMA = schema
return Serializer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment