BrianCas
BrianCas

Reputation: 789

Incorrect type. Expected pk value, received dict. - Django REST

I'm new with Django Rest, I'm having trouble saving my data, I get "Incorrect type. Expected pk value, received dict", do I have to convert the dictionary into a list?

Company Profile Model:

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')

Country Model:

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

Serializers:

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')

Upvotes: 2

Views: 3492

Answers (2)

user3712978
user3712978

Reputation: 167

pk stands for primary key in the django model

Upvotes: 0

romantolkachyov
romantolkachyov

Reputation: 9

The only way you can see this error is to post a list of dicts under countries_id key of request body. You need to pass a list of countries ids (int) instead.

Traceback and request data would be helpful to answer your question exactly.

Upvotes: 1

Related Questions