我将 Django REST Framework 与 HyperlinkedModelSerializer
结合使用
序列化器.py:
class ReportTypesViewSet(viewsets.ModelViewSet):
queryset = ReportType.objects.all()
serializer_class = ReportTypesSerializer
api.py:
class ReportTypesSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ReportType
fields = ('name', 'uuid', 'active', )
现在 API 可以工作了,但超链接的 URL 中有 pk
,例如: http://localhost:8000/api/reporttypes/1/
我想通过 UUID 字段(模型提供的)而不是内部 PK 来映射对象。我知道我可以将主键更改为 UUID 字段,但我读到这会导致其他问题,例如性能下降。
有没有办法可以通过 UUID 引用对象,但仍然在内部使用默认的 pk (id)?
最佳答案
这是你应该做的:
class ReportTypesViewSet(viewsets.ModelViewSet):
queryset = ReportType.objects.all()
serializer_class = ReportTypesSerializer
lookup_field = 'uuid'
这告诉 DRF 您正在使用 uuid 字段进行查找,而不是默认的 pk
关于Django REST框架: URLs without PK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56431755/