Django - "Invalid type. Expected pk error received by str"

I my django-rest-framework I have the following models:

Basically, each trip has one final destination and may have several intermediate destinations.

models.py:

class Destination(models.Model):
    name=models.CharField(max_length=30)

class Ride(models.Model):
    driver = models.ForeignKey('auth.User', related_name='rides_as_driver')
    destination=models.ForeignKey(Destination, related_name='rides_as_final_destination')
    leaving_time=models.TimeField()
    num_of_spots=models.IntegerField()
    passengers=models.ManyToManyField('auth.User', related_name="rides_as_passenger")
    mid_destinations=models.ManyToManyField(Destination, related_name='rides_as_middle_destination')

      

serializers.py - RideSerializer

class RideSerializer(serializers.ModelSerializer):
    driver = serializers.ReadOnlyField(source='driver.user.username')

    class Meta:
        model = Ride
        fields = ('driver', 'destination', 'leaving_time',
                  'num_of_spots', 'passengers', 'mid_destinations')
        read_only_fields = ('driver', 'passengers', 'mid_destinations')

      

Problem - When I try to POST / rides / to add a ride - for example{destination=LA, leaving_time=19:45, num_of_spots=4}

I get an error "destination":["Incorrect type. Expected pk value, received str."]}

a couple of questions:

  • What is this error? if I have an endpoint as a foreign key in the Ride model , does that mean that the destination I'm adding must already be in the Targets table ?

  • How do I fix this error?

+3


source to share


1 answer


The problem is that you are passing the name

bound object Destination

to the serializer instead of passing pk

/ id

object Destination

. So the Django REST framework sees this and complains because it can't resolve LA

into an object.



It looks like you can actually search for aSlugRelatedField

, which allows you to identify objects by slug ( LA

in this case) instead of their primary keys.

+4


source







All Articles