qwertyui90
qwertyui90

Reputation: 201

Override a validation check in Django Rest with ModelSerializer

I went to through related questions and didn't find any solution.

View

class TestList(viewsets.ModelViewSet):

    serializer_class = TestSerializer
    queryset = Test.objects.all()

Model

class Location(models.Model):
    latitude = models.CharField(max_length=100)
    longitude = models.CharField(max_length=100)

class Test(models.Model):
    video_id = models.CharField(max_length=100)
    location = models.ForeignKey(Location)

Serializer

class LocationSerializer(serializers.ModelSerializer):

    class Meta:
        model = Location
        fields = ('latitude', 'longitude')


class TestSerializer(serializers.ModelSerializer):

    def validate_location(self, data):
        if type(data['location']) == dict:
            if not (type(data["location"]["latitude"]) == str and len(data["location"]["latitude"]) < 100):
                raise serializers.ValidationError("Latitude field error")
            if not (type(data["location"]["longitude"]) == str and len(data["location"]["longitude"]) < 100):
                raise serializers.ValidationError("Longitude field error")
        else:
            raise serializers.ValidationError("Wrong type")
        return data

    def create(self, validated_data):
        print validated_data
        loc_details = validated_data.pop('location')
        location = Location.objects.create(**loc_details)
        return Test.objects.create(location=location, **validated_data)

    class Meta:
        model = Test
        fields = ('video_id', 'emotions', 'location')

The ModelSerializer of Test expects location field as pk. But i want to recieve a latitude longitude fields and create a Location object before saving Test model.

Post request format

{
    "video_id": "sdasd",
    "location": {"latitude":"52.345","longitude":"56.756"}
}

I want to take the location details, create location object and then pass that to Test model. I wrote custom validation and tried to override the "Expected pk value error". But its not working. How to override the validation error ?

Upvotes: 1

Views: 1847

Answers (1)

Marin
Marin

Reputation: 1121

In your models add related_name, :

class Location(models.Model):
    latitude = models.CharField(max_length=100)
    longitude = models.CharField(max_length=100)

class Test(models.Model):
    video_id = models.CharField(max_length=100)
    location = models.ForeignKey(Location, related_name='locations')

Make your serializer like this:

class TestSerializer(serializers.ModelSerializer):
    class Meta:
        model = Test

class LocationSerializer(serializers.ModelSerializer):
    locations = TestSerializer(required=False)
    class Meta:
        model = Location

And in your views include only LocationSerializer.

Upvotes: 1

Related Questions