Django Rest Framework和@staticmethod。它有什么好处?

时间:2018-09-23 21:24:24

标签: python django django-rest-framework static-methods

我正在使用serializers.py usign PyCharm编码一些方法。然后我必须编写一种方法来获取名称。

 def get_artist_name(obj):
    return obj.artist.name

然后PyCharm建议我将方法设为静态。

 @staticmethod
 def get_artist_name(obj):
    return obj.artist.name

从那时起,我想知道它的好处是什么?这是个好习惯还是类似的做法?如果有任何关于该特定主题的文档,我可以阅读,谢谢。

1 个答案:

答案 0 :(得分:2)

第一个变体是错误的:如果调用 instance 方法,则第一个参数是 callee x中的x.method(para, meter)) 。所以这意味着您需要这样写:

def get_artist_name(self, obj):
    return obj.artist.name

为了使其正常工作,如documentation of a SerializerMethodField所示。

由于您没有在函数主体中使用 self,因此没有必要使用self参数编写函数。此外,通过不将其设置为@staticmethod,只能使用序列化程序实例正确调用该函数:如果要使用SerializerClass.get_artist_name(None, obj)进行调用,则需要提供一个未使用的第一个参数。这与使用some_serializer.get_artist_name(obj)进行调用形成对比,在@staticmethod中只有一个 explicit 参数。

通过使用SerializerClass.get_artist_name(obj),您可以“协调”两者:现在您可以调用some_serializer.get_artist_name(obj)@staticmethod,并且您的@staticmethod装饰器将确保两者都能正常工作。同样的方式。

除非您认为需要访问序列化程序对象或子类将需要访问(通常,您通常希望避免从子实现中“删除”装饰器),否则使用$('.btn').click(function() {...}可能会更优雅。