[英]Python Django RestFramework route trigger
I'am building an API using python 2.7 and django 1.7 and I'm facing a problem. 我正在使用python 2.7和django 1.7构建API,我遇到了一个问题。 I'm not an expert in Rest Framework but I understand the basic mechanisms. 我不是Rest Framework的专家,但我理解基本机制。
I can resume my problem by giving you an example. 举个例子,我可以恢复我的问题。 I have a route lets say 我有一条路可以说
/api/project/
Django Rest Framework provides me all basic operations for this route and I don't need to write them eg: Django Rest Framework为我提供了这条路线的所有基本操作,我不需要编写它们,例如:
POST, GET, PUT, DELETE => /api/project/
The fact is, I want to do some operation when I create a new project. 事实是,我想在创建一个新项目时做一些操作。 I want to add the id of the user who has created the new project. 我想添加创建新项目的用户的id。
I want to add some kind of trigger/callback to the create function: 我想在create函数中添加一些触发/回调:
class ProjectViewSet(viewsets.ModelViewSet):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
def create(self, request, *args, **kwargs):
I want to keep the internal behavior of Rest Framework (I don't want to rewrite the route functions), but I want the route to do extra stuff and I need the request object in my trigger/callback. 我想保留Rest Framework的内部行为(我不想重写路由函数),但我希望路由做额外的事情,我需要触发/回调中的请求对象。 Something like 就像是
def callback(request, instance):
instance.created_by = request.user
instance.save()
Do you have any ideas? 你有什么想法?
Thank you. 谢谢。
You need to add creator_id field to your serializer as well as to model represented by the resource. 您需要将creator_id字段添加到序列化程序以及资源表示的模型。 Then you can do something like this in your view:- 然后你可以在你的视图中做这样的事情: -
import copy
class ProjectViewSet(viewsets.ModelViewSet):
...
def create(self, request, *args, **kwargs):
data = copy.deepcopy(request.data)
data['creator_id'] = request.user.id
request._data = data
return super(ProjectViewSet, self).create(request, *args, **kwargs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.