我正在使用Django Rest Framework的HyperlinkedModelSerializer,ModelViewset和DefaultRouter,最终得到如下的好网址:http://localhost:8000/api/users/1
。
我想,给定一个用户ID,找到该用户的完全限定的URL,而无需硬编码。给定53,我想要http://localhost:8000/api/users/1
,当我转向生产时主机应该改变。
# from urls.py
router = routers.DefaultRouter()
router.register(r'users', shared_views.UserViewSet)
# from models.py
class UserViewSet(viewsets.ModelViewSet):
'''
endpoint for viewing/editing users
'''
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
# from serializers.py
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
我该怎么做?我试过:reverse(UserViewSet.as_view({'get': 'retrieve'}), args=[request.user.id])
但是出现了这个错误:
反向'shared.views.UserViewSet',参数'(1,)'和关键字参数'{}'未找到。尝试了0种模式:[]
答案 0 :(得分:1)
正如@Anush所说,我可以使用序列化程序来获取URL。请求需要以特定方式作为关键字参数传递(参见下文):
class OwnedViewSet(viewsets.ModelViewSet):
''' ModelViewSets that use hyperlinked model serializers
can inherit this to automatically
set `owner` = current user.
'''
def create(self, request, *args, **kwargs):
serialized_owner = UserSerializer(request.user, context={'request': request})
request.data['owner'] = serialized_owner.data['url']
return super(OwnedViewSet, self).create(request, *args, **kwargs)