django - “类型不正确.预期的 pk 值,收到的 str"错误 [英] django - "Incorrect type. Expected pk value, received str" error

查看:23
本文介绍了django - “类型不正确.预期的 pk 值,收到的 str"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 django-rest-framework 我有以下模型:

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

基本上每个行程都有一个最终目的地,并且可以有多个中间目的地.

Basically every ride has one final destination and can have multiple middle 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')

问题是 - 当我尝试 POST 到/rides/以添加行程时 - 例如 {destination=LA, leave_time=19:45, num_of_spots=4}

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

我收到错误destination":[类型不正确.预期的pk值,已收到str."]}

几个问题:

  • 这是什么错误?如果我在 Ride 模型中有一个目的地作为外键,这是否意味着我要添加的目的地必须已经在 Destinations 表中?

  • What is this error? if I have a destination as a foreign key in the Ride model, does it mean that the destination that I am adding has to be already in the Destinations table?

如何解决这个错误?

推荐答案

问题是您将相关 Destination 对象的 name 传递给序列化程序,而不是传递 Destination 对象的 pk/id.所以 Django REST 框架看到了这一点并抱怨,因为它无法将 LA 解析为对象.

The issue is that you are passing the name of the related Destination object into the serializer, instead of passing the pk/id of the Destination object. So Django REST framework is seeing this and complaining, because it can't resolve LA into an object.

听起来您实际上可能正在寻找 a SlugRelatedField,它允许您通过 slug(在本例中为 LA)而不是它们的主键来识别对象.

It sounds like you may actually be looking for a SlugRelatedField, which allows you to identify objects by a slug (LA in this case) instead of their primary keys.

这篇关于django - “类型不正确.预期的 pk 值,收到的 str"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆