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

Django Rest Framework and @staticmethod. What is the benefit of it?

我在 serializers.py 使用 PyCharm 中编写了一些方法。然后我不得不编写一个方法来获取名称。

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

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

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

从那以后我就想知道它有什么好处?这是一个很好的做法还是类似的东西?如果有任何文档我可以阅读有关此特定主题的信息,请提前致谢。

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

def get_artist_name(<b>self,</b> obj):
    return obj.artist.name

要让它正常工作,正如在documentation of a SerializerMethodField中演示的那样。

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

通过使用 @staticmethod,你 "harmonize" 这两个:现在你可以调用 SerializerClass.get_artist_name(obj)some_serializer.get_artist_name(obj),你 @staticmethod 装饰器将确保两者的工作方式相同。

除非你认为你需要访问序列化器对象,或者子类需要它(通常你想避免子实现中的 "removing" 装饰器),使用 @staticmethod.