How to make an attribute read-only in serializers in DRF?
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?
extra_kwargs = {
'employee': {'read_only': True}
}
You can make it read-only by mentioning it on the serializer, and show the current user's value by modifying the init method in the following way :
class MySerializer(serializers.ModelSerializer):
class Meta:
model = models.MyClass
read_only_fields = [
'employee',
]
def get_employee(self, instance) -> Any:
employee = None
request = self.context.get('request')
if request and hasattr(request, 'user'):
employee = Employee.objects.get(request.user)
# if you want to show serialize value of employee
# then write a EmployeeSerializer and add following blocked code
# if employee:
# serializer = EmployeeSerializer(user, many=False)
# employee = serializer.data
return employee