From 770ed3de2ef8339ec0b74f7eb522283718e01a3b Mon Sep 17 00:00:00 2001 From: Ryan Kaskel Date: Sat, 18 May 2013 13:11:40 +0100 Subject: ToMany fields default to read-only if targeting ManyToManyField. --- rest_framework/serializers.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'rest_framework/serializers.py') diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 7707de7a..75f1e1d0 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -587,11 +587,16 @@ class ModelSerializer(Serializer): forward_rels += [field for field in opts.many_to_many if field.serialize] for model_field in forward_rels: + has_user_through_model = False + if model_field.rel: to_many = isinstance(model_field, models.fields.related.ManyToManyField) related_model = model_field.rel.to + if to_many and not model_field.rel.through._meta.auto_created: + has_user_through_model = True + if model_field.rel and nested: if len(inspect.getargspec(self.get_nested_field).args) == 2: warnings.warn( @@ -620,6 +625,9 @@ class ModelSerializer(Serializer): field = self.get_field(model_field) if field: + if has_user_through_model: + field.read_only = True + ret[model_field.name] = field # Deal with reverse relationships @@ -637,6 +645,12 @@ class ModelSerializer(Serializer): continue related_model = relation.model to_many = relation.field.rel.multiple + has_user_through_model = False + is_m2m = isinstance(relation.field, + models.fields.related.ManyToManyField) + + if is_m2m and not relation.field.rel.through._meta.auto_created: + has_user_through_model = True if nested: field = self.get_nested_field(None, related_model, to_many) @@ -644,6 +658,9 @@ class ModelSerializer(Serializer): field = self.get_related_field(None, related_model, to_many) if field: + if has_user_through_model: + field.read_only = True + ret[accessor_name] = field # Add the `read_only` flag to any fields that have bee specified -- cgit v1.2.3