Handling field names that conflict with serializer attributes? #8969
Replies: 1 comment
-
Hi! This is an old question, but I found this while looking for answers to my problem, so I'll add this for posterity. (Because of Wisdom of the Ancients) I had a similar problem in my code recently. My model has a This works fine in practice, since DRF moves all Fields in the object to What I did was to declare the field as a field, which satisfies both mypy and pyright:
In the OP's case the following should help: class FooSerializer(serializers.Serializer):
# All serializer Fields are moved into _declared_fields when the
# metaclass creates the Serializer object, but the type checker
# will think that `data` is a property, because it is defined as
# such, so we have to assure it, that, only in this subclass, it's
# a field.
label: serializers.Field = serializers.CharField(max_length=10) Cheers! |
Beta Was this translation helpful? Give feedback.
-
I have a data structure I need to validate which has a field called
label
. However, serializers have an attribute on them calledlabel
. Trying to set the field is overwriting the attribute which mypy (correctly) complains about:I can rename the field and change the
source
so that it will serialize the object correctly:However, the
source
argument only affects serializing, not deserializing:Is it possible to do this without hacking together something in an override?
Beta Was this translation helpful? Give feedback.
All reactions