Home > front end >  How to make an attribute read-only in serializers in DRF?
How to make an attribute read-only in serializers in DRF?

Time:01-24

I have a serializer.

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.MyClass

My model class is:

class MyClass(models.Model):
    employee = models.ForeignKey("Employee", on_delete=models.CASCADE)
    work_done = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

I want employee attribute to be read-only and should only show this value in it's field:

employee = Employee.objects.get(user=self.request.user)

How can I do this in serializers?

CodePudding user response:

extra_kwargs = {
            'employee': {'read_only': True}
       }

CodePudding user response:

You can make an attribute read-only in a serializer by specifying the read_only attribute in the serializer field.

Example of how you can make the employee attribute read-only in the MySerializer class:

class MySerializer(serializers.ModelSerializer):
    employee = serializers.SerializerMethodField()

    class Meta:
        model = models.MyClass
        fields = ('employee', 'work_done', 'created_at', 'updated_at')

    def get_employee(self, obj):
        request = self.context.get("request")
        employee = Employee.objects.get(user=request.user)
        return employee.id

In this example, I have used SerializerMethodField and defined a method get_employee which retrieves the current user from the request object using request.user and return the id of the employee, so that it will be read-only.

Also, you can only show the field that you want by specifying the fields in the Meta class.

Please let me know if you have any further question. I apologize again for the confusion caused by my previous response.

  • Related