Using ModelSerializer class nested inside Serilaizer class to validate field and return object

I'm trying to validate user input by passing the data to a Serializer class. The said serializer class has no models and inherits from serializers.Serializer.

I'm trying to validate if the input is present in a ModelSerializer class called Country. My code keeps returning the following error: value already exits.

Things I have tried:

  • field level validation using a method called: validate_country - which works.

I wanted to know if the same could be achieved by calling Country serializer class from inside ValidationSerializer.

models.py

class Country(models.Model):
    iso_code = models.CharField(max_length=2, unique=True)
    name = models.CharField(max_length=255)

    class Meta:
        ordering = ("name",)
        verbose_name_plural = _("Countries")

    def __str__(self):
        return self.name

serializers.py

class CountrySerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = ("id", "name", "iso_code")


class ValidationSerializer(serializers.Serializers):
    
    # this serializer does not have a model and only want to validate inputs provided by user

    country = ListField(child=CountrySerializer(many=False, required=False), default=list, allow_empty=True)
    
    # sample country input looks like: {"country": ["US", "CA", "GB"]}
    # I want to pass the country codes to CountrySerializer to validate if the country codes exists and return a seriliazed object

views.py

class MyView(GenericAPIView):

    def get(self):
        country=request.query_params['country'].split(",")
        ser = ValidationSerializer(data=country)
        if not ser.is_valid()
            return Response(ser.errors)
        else:
            #process request

Thank you !

Back to Top