From b5e8187e5d58e1534279e384caec19c595daf5e3 Mon Sep 17 00:00:00 2001 From: Maximiliano Date: Wed, 8 Nov 2017 14:54:57 +0100 Subject: [PATCH] Example code don't check for non existing fields The behavior of DynamicFieldsModelSerializer when passing a non-existent (with a typo for example) field is confusing: * The field will not appear in the serializer output as expected * The error isn't caught anywhere (which can be frustrating to debug) This assert takes care of this. Maybe there is a better way to throw an exception than this, feedback welcome. BTW, I could imagine having this functionality in a mixin. What do you think about it? Let me know --- docs/api-guide/serializers.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 0e235c88d..355204d7c 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -1074,6 +1074,11 @@ For example, if you wanted to be able to set which fields should be used by a se # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields.keys()) + + # Catch fields that don't exist + non_existing = allowed - existing + assert len(non_existing) == 0, 'Invalid fields: {}'.format(non_existing) + for field_name in existing - allowed: self.fields.pop(field_name)