【问题标题】:Django Rest Framework and @staticmethod. What is the benefit of it?Django Rest 框架和@staticmethod。它有什么好处?
【发布时间】:2018-09-23 21:24:23
【问题描述】:

我在 serializers.py ussign PyCharm 中编写了一些方法。然后我必须编写一个方法来获取名称。

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

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

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

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

【问题讨论】:

  • 如果您不将其设为静态,则obj 将采用self 参数(您调用它的序列化程序)。

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


【解决方案1】:

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

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,您可以“协调”两者:现在您可以调用SerializerClass.get_artist_name(obj)some_serializer.get_artist_name(obj),而您的@staticmethod 装饰器将确保两者的工作方式相同。

除非您认为您需要访问序列化程序对象,或者子类需要访问(通常您希望避免从子实现中“移除”装饰器),否则使用@staticmethod 可能更优雅。

【讨论】:

    猜你喜欢
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 2011-10-31
    • 1970-01-01
    • 2017-12-19
    • 2016-08-21
    • 2015-01-04
    相关资源
    最近更新 更多