Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework - PrimaryKeyRelatedField

I am following the Django REST framework tutorial, and I am at this point here: http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions#adding-endpoints-for-our-user-models

My code for UserSerializer looks like:

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

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

I am trying to understand what is PrimaryKeyRelatedField exactly. To do so I am doing changing the code as follows and refreshing the URL http://127.0.0.1:8000/users/ to see different outputs

Variation 1

snippets = serializers.RelatedField(many=True, read_only=True)


{
    "count": 1, 
    "next": null, 
    "previous": null, 
    "results": [
        {
            "id": 1, 
            "username": "som", 
            "snippets": [
                "Snippet title = hello", 
                "Snippet title = New2"
            ]
        }
    ]
}

This is printing out the __unicode__() value of the snippets. I expected this

Variation 2 - using PrimaryKeyRelatedField

snippets = serializers.PrimaryKeyRelatedField(many=True, read_only=True)


{
    "count": 1, 
    "next": null, 
    "previous": null, 
    "results": [
        {
            "id": 1, 
            "username": "som", 
            "snippets": [
                1, 
                2
            ]
        }
    ]
}

This prints out the primary key id of the two snippets - I don't understand this

Variation 3 - commenting out also produces

#snippets = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

{
    "count": 1, 
    "next": null, 
    "previous": null, 
    "results": [
        {
            "id": 1, 
            "username": "som", 
            "snippets": [
                1, 
                2
            ]
        }
    ]
}
like image 974
dowjones123 Avatar asked Jun 21 '14 23:06

dowjones123


1 Answers

From the Serializer Docs

The default ModelSerializer uses primary keys for relationships

If you don't specify anything yourself PrimaryKeyRelatedField will be used under the hood, so your Variation 2 is the expected output.

Hopefully that helps.

like image 98
Carlton Gibson Avatar answered Oct 07 '22 21:10

Carlton Gibson