Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework Serializer charfield not updating when source is given

I have a model field with choices charfield

class Vehicle(models.Model):
    name = models.CharField(max_length=100)

    STATUS_CHOICES = (
        ("N", "New"),
        ("U", "Used"),
        ("P", "Just Purchased")
    )
    status = models.CharField(max_length=3, choices=STATUS_CHOICES)

The serializer class also has charfield for status but with source argument to display the readable value

class VehicleSerializer(ModelSerializer):
    status = serializers.CharField(source='get_status_display')

    class Meta:
        model = Vehicle

When I try to update vehicles through patch request with data {'status': "U"}, there is no update performed. However the update occurs when I remove the source from serializer status field. Providing source is necessary to display proper value in web view.

I know the option of changing the name of status in serializer to something other and using that in the template. Also there is the option to override update method in serializer, however my question is what is source doing to prevent the update?

like image 514
Raj Subit Avatar asked Nov 08 '22 23:11

Raj Subit


1 Answers

I think you need to add status to the fields list in meta.

class VehicleSerializer(ModelSerializer):
     status = serializers.CharField(source='get_status_display')

     class Meta:
         model = Vehicle
         fields = ('status',)
like image 85
hspandher Avatar answered Nov 15 '22 06:11

hspandher