Home > database >  Validation error in Django 'POST' request
Validation error in Django 'POST' request

Time:11-24

I'm a beginner with Django Rest Framework

I've created a model and serializer for it. There it goes:

models.py

class Car(models.Model):
    make = models.CharField(max_length=15)
    model = models.CharField(max_length=15)

    def __str__(self):
        return self.make


class CarRate(models.Model):
    rate = models.ForeignKey(Car, related_name='rates', on_delete=models.CASCADE)

serializers.py

class CarRateSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = CarRate
        fields = ('rate')

class CarSerializer(serializers.HyperlinkedModelSerializer):
    rates = CarRateSerializer(many=True)
    '''rates = serializers.PrimaryKeyRelatedField(
        many=True,
        read_only=False,
        queryset=CarRate.objects.all()
    )'''

    def create(self, validated_data):
        rates_data = validated_data.pop("rates")
        car = Car.objects.create(**validated_data)
        for rate_data in rates_data:
            CarRate.objects.create(car=car, **rate_data)
        return car

    class Meta:
        model = Car
        fields = ('id', 'make', 'model', 'rates')

What I want to do is to add a rate for a Car with a specific ID with a POST method and JSON, but when I do it multiple times it stores all the rates for that one object. I will add a rate like that:

{
    "id":2,
    "rate":4
}

So here is my POST method, but it gives a response Car id not found so it doesn't pass validation.

views.py

@api_view(['POST'])
def car_rate(request):

    if request.method == 'POST':
        rate_data = JSONParser().parse(request)
        rate_serializer = CarSerializer(data=rate_data)

        if rate_serializer.is_valid():
        
            ''' Code that checks if a rate is from 1 to 5 '''

        return JsonResponse({'message': 'Car id not found!'})

So what I think might be a problem, that CarSerializer needs more fields than just one rate field and I should somehow pass just a rate to that car, But don't know how.

CodePudding user response:

Your car rate models actually doest have a field to store 'rate', the current rate field stores car data not rates. So change your CarRate model to

class CarRate(models.Model):
    car = models.ForeignKey(Car, related_name='rates', on_delete=models.CASCADE)
    rate = models.PositiveIntegerField(default=0)

Serializer

class CarRateSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = CarRate
        fields = ('__all__')

car_rate view

@api_view(['POST'])
def car_rate(request):

    if request.method == 'POST':
        rate_data = JSONParser().parse(request)
        rate_serializer = CarRateSerializer(data=rate_data) #Changed Serializer class

        if rate_serializer.is_valid():
        
            ''' Code that checks if a rate is from 1 to 5 '''
            return JsonResponse({'message': 'valid'})

        return JsonResponse({'message': 'Car id not found!'})
  • Related