Home > other >  How can I retrieve the return value of a method of a class within the same class?
How can I retrieve the return value of a method of a class within the same class?

Time:09-09

I was wondering if I could get any insight on this.

So far, I have this class:

class MaterialTaggingListView(ServerSideDatatableView):
    def get_queryset(self):
        vLatestUpdateDate = ScTaggingLargeTableIp.objects.values('update_date').order_by('-update_date')[:1]
        request = self.request
        if 'selectedcountries' not in request.session:
            vSelectedCountries = ['CN']
        else:
            vSelectedCountries = request.session['selectedcountries'] 
            vSelectedPlants =request.session['selectedplants'] 
            vSelectedValClass = request.session['selectedvalclass'] 
            vSelectedCoCode = request.session['selectedcocode'] 
           columns = request.session['selectedtags']            
        return ScTaggingLargeTableIp.objects.filter(update_date = vLatestUpdateDate,plant_country__in=(vSelectedCountries), plant__in=(vSelectedPlants), valclass__in=(vSelectedValClass), company_code__in=(vSelectedCoCode))

    def set_columns(self): 
       request = self.request
       columns = request.session['selectedtags']
       return columns

    columns = set_columns()

With this code above, I got the error: missing 1 required positional argument: 'self' Can anyone tell me if what I'm trying to do is possible and how I could resolve the error.

CodePudding user response:

Usually, you need to initialize class attributes in __init__ method for this to work, because you cannot set the attribute to the object that has not been created yet.

But since you are using self.request object in the set_columns method, you need to override the setup method in which request object is initialized:

class MaterialTaggingListView(ServerSideDatatableView):
    def setup(self, request, *args, **kwargs):
        super().setup(request, *args, **kwargs)
        self.columns = self.set_columns()

CodePudding user response:

No, you can't do that. You need to create an instance of a class to call non-class methods on it. What you can do - is either not set columns as a class-level variable, or make set_columns a classmethod, but in that case it won't be able to receive request in it (Django will create an instance of your view before processing request).

If you want to persist columns value between requests - store it in database or in cache.

  • Related