[Django]-"AttributeError" And PrimaryKeyRelatedField in Django Rest Framework

1👍

use snippets not snippet, try with

class UserSerializer(serializers.ModelSerializer):
    snippets = serializers.PrimaryKeyRelatedField(many=True)

    class Meta:
        model = User
        fields = ('id', 'username','snippets')

2👍

Please take a look at your snippets/models.py

owner = models.ForeignKey('auth.User', related_name='snippets')

The thing you missed is related_name argument.

class UserSerializer(serializers.ModelSerializer):
    snippets = serializers.PrimaryKeyRelatedField(many=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'snippets')

related_name argument on related model ForeignKey should match both “field name” of you serializer also be inside fields tuple.

👤rivf

0👍

Here is another way of doing this

class snippetSerializer(serializers.PrimaryKeyRelatedField, serializers.ModelSerialier):
    class Meta:
       model = Snippet
       fields = '__all__'



class UserSerializer(serializers.ModelSerializer):
   snippets = snippetSeriazlier(many=True, queryset=Snippet.objects.all())

   class Meta:
       model = User
       fields = ('id', 'username','snippets')

Leave a comment