Created
February 26, 2014 20:34
-
-
Save Kobold/9237949 to your computer and use it in GitHub Desktop.
A default read-only serializer for django-rest-framework as of DRF 2.4.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RestrictedSerializerOptions(serializers.ModelSerializerOptions): | |
""" | |
Meta class options for ModelSerializer | |
""" | |
def __init__(self, meta): | |
super(RestrictedSerializerOptions, self).__init__(meta) | |
self.writable_fields = getattr(meta, 'writable_fields', ()) | |
class WriteRestrictedModelSerializer(serializers.ModelSerializer): | |
""" | |
A ModelSerializer that takes an additional `writable_fields` argument that | |
controls which fields can be written to. | |
""" | |
_options_class = RestrictedSerializerOptions | |
def __init__(self, *args, **kwargs): | |
super(WriteRestrictedModelSerializer, self).__init__(*args, **kwargs) | |
# Any fields not writable are set to read_only. | |
writable = set(self.opts.writable_fields) | |
existing = set(self.fields.keys()) | |
for field_name in existing - writable: | |
self.fields[field_name].read_only = True | |
""" | |
Use will look something like: | |
class TourSerializer(WriteRestrictedModelSerializer): | |
building = BuildingSerializer() | |
class Meta: | |
model = Tour | |
writable_fields = ('time',) | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment