I'd like to serialise a model with a lot of choices like such:
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 love that the default serializer such as:
class HouseView(generics.ListCreateAPIView):
model = House
serializer_class = HouseSerializer
class HouseSerializer(serializers.ModelSerializer):
class Meta:
model = House
works great if I want just the integer value
{accessibility:1}
However, what I'd like to get
{accessibility:'Full'}
Help is kindly appreciated. Many thanks.
In function based views we can pass extra context to serializer with "context" parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with "self. context". From example, to get "exclude_email_list" we just used code 'exclude_email_list = self.
read_only. Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.
Serializer Method FieldIt gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. SerializerMethodField gets its data by calling get_<field_name> . Example: class UserSerializer(serializers.
IntegerField is a integer number represented in Python by a int instance. This field is generally used to store integer numbers in the database. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise.
You can get a read-only serializer field with the verbose value of a model field with choices through the get_FOO_display
method. This method is added automatically when setting choices on a field. You can set that method as the source for a character field.
For endpoints that also support writing data, I would recommend to add the "normal" field, and another read-only field with the _name
extension.
In your example, the following should produce the output you are looking for. The accessibility_name
is read-only, while the accessibility
is there to allow writing / updating values.
class HouseSerializer(serializers.ModelSerializer):
accessibility_name = serializers.CharField(source='get_accessibility_display')
class Meta:
model = House
fields = ('accessibility', 'accessibility_name', )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With