Chi*_*fir 6 python django django-rest-framework
如何在 DRF 视图集中更改自定义操作的默认查找参数?这是我的视图集(简化)
class InvitationViewSet(MultiSerializerViewSet):
queryset = Invitation.objects.all()
@action(
detail=False,
#url_path='accept-invitation/<str:key>/',
#lookup_field='key'
)
def accept_invitation(self, request, key=None):
invitation = self.get_object()
with legal_invitation(invitation):
serializer = self.get_serializer(invitation)
invitation.accepted = True
invitation.save()
return Response(serializer.data)
Run Code Online (Sandbox Code Playgroud)
我希望当用户输入 url 时/invitations/accept-invitation/abccba,其中abccba是随机令牌字符串。key- 是邀请模型中的一个独特字段。我知道我可以设置 per-Viewset lookup_field='key',但我希望所有其他操作仍然使用 default lookup_field='pk'。我怎样才能达到我想要的?
您可以重写该get_object()方法来实现这一目标。这是GenericAPIView代码:
def get_object(self):
"""
Returns the object the view is displaying.
You may want to override this if you need to provide non-standard
queryset lookups. Eg if objects are referenced using multiple
keyword arguments in the url conf.
"""
queryset = self.filter_queryset(self.get_queryset())
# Perform the lookup filtering.
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
assert lookup_url_kwarg in self.kwargs, (
'Expected view %s to be called with a URL keyword argument '
'named "%s". Fix your URL conf, or set the `.lookup_field` '
'attribute on the view correctly.' %
(self.__class__.__name__, lookup_url_kwarg)
)
filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
obj = get_object_or_404(queryset, **filter_kwargs)
# May raise a permission denied
self.check_object_permissions(self.request, obj)
return obj
Run Code Online (Sandbox Code Playgroud)
然后添加一个验证来检查当前正在触发哪个操作并相应地修改lookup_field/ lookup_url_kwarg。你的函数self.action内部get_object应该等于accept_invitation(你正在装饰的函数的名称)。
但这里的问题是您正在使用带有 的动作装饰器detail=False,因此查找字段没有多大意义。我的方法适用于评论之一中提到的常规详细路线:<your_api_url>/<invitation-viewset-path>/<key>/accept-invitation/。
| 归档时间: |
|
| 查看次数: |
2082 次 |
| 最近记录: |