how to patch only the foreign key of a nested serializer in django rest framework?

Solution for how to patch only the foreign key of a nested serializer in django rest framework?
is Given Below:

I have a nested serializer which binds some fields that are foreign keys to the related objects, when i make a get request I get the data as I want it, but when I make a patch request I would like to be able to only provide the foreign key id instead of the whole object representation.


class Preferences(models.Model):
    user = models.ForeignKey(User, related_name="preferences", on_delete=models.CASCADE)
    current_patient = models.ForeignKey(Patient, null=True, on_delete=models.CASCADE, default=None)
    current_professional = models.ForeignKey(Professional, null=True, on_delete=models.CASCADE, default=None)
    current_entity = models.ForeignKey(Entity, null=True, on_delete=models.CASCADE, default=None)
    current_supervisor = models.ForeignKey(Supervisor, null=True, on_delete=models.CASCADE, default=None)

class PreferencesSerializer(serializers.ModelSerializer):
    current_patient = PatientSerializer(many=False)
    current_professional = ProfessionalSerializer(many=False)
    current_entity = EntitySerializer(many=False)
    current_supervisor = SupervisorSerializer(many=False)

    class Meta:
        model = Preferences

class PreferencesView(generics.RetrieveUpdateAPIView):
    serializer_class = PreferencesSerializer

    def get_object(self):
        return Preferences.objects.get(user=self.request.user)

You can override your view’s get_serializer_class method:

class PreferencesView(generics.RetrieveUpdateAPIView):
    def get_serializer_class(self):
        if self.request.method == "PATCH":
            return PatchPreferencesSerializer

        return PreferencesSerializer
    # ...

Please refer to Django REST documentation: