django rest framework change primary key to use a unqiue field

后端 未结 3 1604
情话喂你
情话喂你 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:44

    In order to get the URLs to work, you might need to add lookup_field on the ViewSet, not just on the serializer. So you would have:

    class GameProfileViewSet(viewsets.ModelViewSet):
        queryset = GameProfile.objects.all()
        serializer_class = GameProfileSerializer
        lookup_field = 'user__id'
    

    In this case the lookup_field uses the double-underscore notation rather than the dot notation (dots won't work in the regular expressions in the URL patterns). I was unable to get the solution proposed by @almalki and @patsweet to work; according to the documentation on serializers, "The value of this option [lookup_field] should correspond both with a kwarg in the URL conf, and with a field on the model", so it's possible that it doesn't work with RelatedFields.

提交回复
热议问题