django-rest-framework icon indicating copy to clipboard operation
django-rest-framework copied to clipboard

Not possible to override serializer_field_mappings with a field that has choices (for example a from ChoiceField derived field)

Open gabn88 opened this issue 2 years ago • 4 comments

Because of this line:

https://github.com/encode/django-rest-framework/blame/0abb84fa3955956fc6156cc2c51222cd4ceae783/rest_framework/serializers.py#L1286

If you set a serializer_field_mapping to for example a fields.CountryField: serializer_fields.CountryField (from django_countries), it will be replaced by a 'dumb' ChoiceField and the serialization will fail. This makes that you have to manually set this field on every serializer and the serializer_field_mapping mechanism won't work.

Another example is the TimeZoneField (if you use the extended version that shows the choices via the OPTIONS request).

gabn88 avatar Dec 04 '23 19:12 gabn88

My suggestion is to change

field_class = self.serializer_choice_field

to:

if not issubclass(field_class, self.serializer_choice_field):
            field_class = self.serializer_choice_field

That way you enable developers to override the serializer_field_mapping also for ChoiceFields (now this is impossible).

gabn88 avatar Dec 05 '23 08:12 gabn88

@gabn88 can i start contributing to this ?

Pavankumardontha avatar Dec 05 '23 22:12 Pavankumardontha

@Pavankumardontha that would be great.

I had to change the custom ChoiceFields (CountryField / TimezoneField) also a little, because they need the argument 'choices' and other arguments (for example 'countries') won't be passed along. Something to keep in mind.

gabn88 avatar Dec 14 '23 14:12 gabn88