django rest framework change primary key to use a unqiue field

后端 未结 3 1613
情话喂你
情话喂你 2021-02-07 06:48

I have a model which is called GameProfile, which is a one to one relation with User model. I used HyperlinkedModelSerializer across all m

3条回答
  •  我寻月下人不归
    2021-02-07 07:53

    Assuming your GameProfile model looks like:

    class GameProfile(models.Model)
        user = models.OneToOneField('User')
    

    The serializer will be:

    class GameProfileSerializer(serializers.HyperlinkedModelSerializer):
        user_id = serializers.Field(source='user.id')
    
        class Meta:
            model = GameProfile
    

    Set the .lookup_field attribute on the view correctly:

        lookup_field = 'user_id'
    

    Url will be:

    /gameprofile/
    

提交回复
热议问题