Python3-DRF覆盖类构造函数

时间:2018-12-13 19:05:36

标签: python class django-rest-framework override self

我知道这很容易做到,但此刻我有点困惑。

我有一堂课

class CustomListView(view.CustomView, generic.ListApiView):

    queryset = models.Custom.objects.all()
    serializer_class = serializers.CustomListSerializer

    def perform_instance(self):
       url = self.request.path_info
       ... some stuff
       custom_obj = {...}
       return custom_obj

    def get_queryset(self):
        obj = self.perform_instance()
        ...

    def get_serializer_class(self):
        obj = self.custom_obj()

我需要以使custom_obj成为 class属性的方式构建类(因此,perform_instance在构建类时将只调用一次),并且self.obj实例可以访问custom_obj在get_querysetget_serializer_class内部。

我尝试用不同的方式调用super()__init__并实例化了perform_instance,但是我找不到解决方法。

我尝试过这样的事情:

class CustomListView(view.CustomView, generic.ListApiView):

    queryset = models.Custom.objects.all()
    serializer_class = serializers.CustomListSerializer

    def __init__(self, *args, **kwargs):
        obj_instances = self.perform_instance()
        """ or self["obj_instances"] = self.perform_instance() 
        assigning obj_instance as class variable and more"""

        super(CustomListView, self).__init__(*args, **kwargs)

    def perform_instance(self):
        ...

    def get_queryset(self):
        obj = self.obj_instance
        ...

1 个答案:

答案 0 :(得分:0)

首先,您应该知道该视图是在每个请求中创建的。因此,除非您使用的caching mechanism超出了我的问题范围,否则必须为每个请求计算DoCmd.GoToRecord acDataForm, Me.Name, acNewRec 其次,您要获取的是 instance 属性而不是class属性。 选中the difference

考虑了所有这些因素后,您可以使用python custom_obj装饰器以这种方式实现所需的功能:

@property

现在您可以致电@property def custom_obj(self): # property caching mecahnism if not hasattr(self, '_custom_obj'): ... some caluculation... self._custom_object = {...} return self._custom_obj