0

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 ... list-view 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?

Mario
  • 339
  • 4
  • 17
  • You can use this (https://stackoverflow.com/a/31202901/1268926) to check if the value has changed and then fire a task/whatever you need to in the model save method – Kedar Jun 18 '21 at 11:10
  • This answer, along with other comments in the same question, seem to all revolve around saving, or after some sort of request. It is a step I think, but unfortunately I don't think it might be applicable in my usecase. What I wish for is: - You open up the DRF API interface to `/mymodel/1/` - The django form below has `field_one` as a text input, `field_two` as a text input, and `choices_field` as a dropdown selection. - I click `choices_field` and change the option from the dropdown and this is where I want to execute my own event. Maybe change the choices, or switch serializers, etc .. – Mario Jun 18 '21 at 11:13
  • You haven't mentioned any other constraints you have.. there's not much else to work with – Kedar Jun 18 '21 at 11:16
  • Apologies, I pressed Return rather than Shift + Return so it prematurely sent the message :) – Mario Jun 18 '21 at 11:16
  • 1
    Okay so you need dynamic behaviour on the front-end. You will need to customise the browsable API DRF offers: https://www.django-rest-framework.org/topics/browsable-api/#customizing (add some javascript there) – Kedar Jun 18 '21 at 11:20
  • This looks very promising, thank you! I'll update if this works or not, and will mark as accepted answer if it does. – Mario Jun 18 '21 at 11:21

0 Answers0