Serialise selection text for IntegerField with selection

I would like to serialize a model with a large selection, for example:

class House(models.Model): ACCESSIBILITY_CHOICES = ( (ACCESSIBILITY_FULL, 'Full'), (ACCESSIBILITY_PARTIAL, 'Partial'), (ACCESSIBILITY_NONE, 'None') ) accessibility = models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES, null=True) 

I like the default serializer, for example:

 class HouseView(generics.ListCreateAPIView): model = House serializer_class = HouseSerializer class HouseSerializer(serializers.ModelSerializer): class Meta: model = House 

works fine if i want only integer value

 {accessibility:1} 

However, what I would like to get

 {accessibility:'Full'} 

Help is kindly appreciated. Thank you very much.

+6
source share
2 answers

Specify a selection in the serializer field with raw values, such as ...

 ACCESSIBILITY_CHOICES = ( ('Full', 'Full'), ('Partial', 'Partial'), ('None', 'None') ) 

Then take a look at the redefinition of the "to_native" method so that the string values ​​translate to their integer equivalents.

This should give you an external API that uses string representations, but a backend that uses integer representations.

+1
source

You can get a read-only serializer field with a detailed value of the model field with the get_FOO_display options. This method is added automatically when you configure the selection in the field. You can set this method as the source for the character field.

For endpoints that also support data writing, I would recommend adding a “normal” field and another read-only field with the extension _name .

In your example, the following should contain the output you are looking for. accessibility_name is read-only, and accessibility is the ability to write / update values.

 class HouseSerializer(serializers.ModelSerializer): accessibility_name = serializers.CharField(source='get_accessibility_display') class Meta: model = House fields = ('accessibility', 'accessibility_name', ) 
+6
source

Source: https://habr.com/ru/post/958519/


All Articles