我在Django中有一个Rest API,并且在扩展ModelViewSet的类中有以下方法:
@custom_decorator
@action(methods=['get'], detail=False, url_name="byname", url_path="byname")
def get_by_name(self, request):
# get query params from get request
username = request.query_params["username"]
experiment = request.query_params["experiment"]
如果删除第一个注释器,则一切正常。但是,当我尝试使用两个装饰器调用此函数时,它甚至都找不到特定的URL路径。是否可以将多个装饰器与@action装饰器一起使用?
最佳答案
我遇到了相同的问题,并通过以下方式解决了该问题:
from functools import wraps
def custom_decorator(func):
# ADD THIS LINE TO YOUR CUSTOM DECORATOR
@wraps(func)
def func_wrapper(*args, **kwargs):
return func(*args, **kwargs)
return func_wrapper
@action(methods=['get'], detail=False, url_name="byname", url_path="byname")
@custom_decorator
def get_by_name(self, request):
# other code
我认为问题在于操作修饰器在添加
custom_decorator
后无法识别该函数,因为名称已更改,因此通过添加@wraps(func)
可以使函数名称保持不变。 (@wraps docs)
关于Django Rest-将@action与自定义装饰器一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59195709/