类型不正确。预期pk值,已收到字典。 -Django REST

时间:2018-06-19 20:12:42

标签: python django rest

我是Django Rest的新手,我在保存数据时遇到问题,出现“类型错误。期望的pk值,收到了字典”,我是否必须将字典转换为列表?

公司资料模型:

class CompanyProfile(models.Model):
    name = models.CharField(_('nombre'), max_length=255, db_index=True)
    email = models.EmailField(_('email de contacto'), max_length=255, blank=True)
    description = HTMLField(_('descripción'), blank=True)
    countries = models.ManyToManyField('countries.Country', blank=True, related_name='countries')

国家/地区型号:

class Country(models.Model):
    name = models.CharField(_('nombre'), max_length=255)
    description = HTMLField(_('descripción'), blank=True)

序列化器:

class CompanyWriteSerializer(serializers.ModelSerializer):
    countries_id = serializers.PrimaryKeyRelatedField(queryset=Country.objects.all(), write_only=True, many=True)
    def create(self, validated_data):
        countries = validated_data.pop('countries_id')
        company = CompanyProfile.objects.register_company(**validated_data,
                                                      country=self.context['request'].user.country.id)
        for c in countries:
            print(c)
            company.countries.add(c)
        return company

    def update(self, instance, validated_data):
        instance.countries = validated_data.get('countries_id', instance.countries)
        instance.save()
        return instance

    class Meta:
        model = CompanyProfile
        fields = ('countries_id', 'countries')

2 个答案:

答案 0 :(得分:0)

看到此错误的唯一方法是在请求正文的countries_id键下发布字典列表。您需要改为传递国家/地区ID(int)的列表。

跟踪和请求数据将有助于准确回答您的问题。

答案 1 :(得分:0)

pk代表Django模型中的主键