1

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.

1
  • In car model you dont have field to that you reference foreign key in car rate model !! I think you should add field to car model (rate) Commented Nov 23, 2021 at 8:34

1 Answer 1

1

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!'})
Sign up to request clarification or add additional context in comments.

7 Comments

Nice, the validation works! By the way I have quick question on that topic and since you are a little bit fammiliar with the classes above, it might be easy for you to give me an answer. I want to save validated rate in the car with given ID. Here's my fragment of code: link
to save data just call rate_serializer.save() inside if rate_serializer.is_valid block.
Oookayy, so first did that but I had an error: FOREIGN KEY constraint failed. All migrations was made and I thought it was problem with save method, that's why I asked.
can you share the full error traceback?
My traceback (I think): link May it be something that the Car object doesn't exist? I add cars with 'make' and 'model' rows through another POST method and later I can list all added cars via GET method so I think Car objects exists.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.