I have a serializer field of type ChoiceField which I populate with a list of tuple values in a list view. What I want is effectively an event listener for that field, where each time the user updates the field (i.e. chooses a different option), a function is called in the back end.
Is this even possible at the moment? Any help is highly appreciated, but as the actual project contains sensitive information, I'll try my best to recreate using a dummy model, view, etc...
models.py
from django.db import models
class MyModel(models.Model):
  field_one = models.TextField()
  field_two = models.TextField()
serializers.py
from models import MyModel
from rest_framework import serializers
class MyModelSerializer(serializers.ModelSerializer):
  CHOICES = (
    (1, 'choice1'),
    (2, 'choice2'),
     ...
  )
  choices_field = serializers.ChoiceField(
    choices=CHOICES,
    label="Model choice",
    default=1,
    write_only=True
  )
  class Meta:
    model = MyModel
    fields = (
      "field_one",
      "field_two",
      "choices_field",
    )
    # non_personal_fields, extra_kwargs etc...
views.py
from models import MyModel
from rest_framework import mixins, viewsets
from serializers import MyModelSerializer
class MyModelViewSet(
  mixins.ListModelMixin,
  mixins.CreateModelMixin,
  mixins.RetrieveModelMixin,
  viewsets.GenericViewSet,
):
  queryset = MyModel.objects.all()
Example usecase:
I have the above model / serializer / viewset, and I visit the endpoint in my browser. This is what I should see ...
Now imagine I click on the Choice dropdown and change CHOICE1 to become CHOICE2. I want the backend (the viewset or the serializer) to listen to that event and execute some code ... For the purposes of this example, let's say I want to switch to another serializer, that would be something along the lines of:
def _switch_serializers(self, choice):
  if choice == 1:
    return MyModelSerializer
  elif choice == 2:
    return SerializerX
  else:
    raise serializers.ValidationError("Invalid choice provided!")
Is this possible? Where would this code live?