Home > Blockchain >  Django querysets using __lte
Django querysets using __lte

Time:07-23

Can I do something like this in django/python without hardcoding it?

def get_rating_average(self, type):
               return list(super().aggregate(Avg(type)).values())[0]

def filter_rating_average_under(self, type):
               return super().filter(type__lte=self.get_rating_average(type=type))
               # FILTER WHERE rating_type is smaller than average type keyword#

#In my views.py I call something like this:

    context['item8'] = Stock.aggregators.filter_rating_average_under(type='mykeyword')

I dont want to hardcode a keyword into a field so is there a way to format this code? So that {type}__lte works and I can run this query with different keywords instead of only one?

CodePudding user response:

Yes, you can use:

from django.db.models import Q

def get_rating_average(self, type):
    return super().aggregate(result=Avg(type))['result']

def filter_rating_average_under(self, type):
    return super().filter(
        Q((f'{type}__lte', self.get_rating_average(type=type)))
    )
  • Related