Search code examples
pythondjangodjango-modelsgetattr

Django - Use getattr() to retrieve Model Method (@property)


I would like to do this:

def retrieve_data(self, variable):
    start_date = datetime.date.today() - datetime.timedelta(int(self.kwargs['days']))
    invoice_set = InvoiceRecord.objects.filter(sale_date__gte=start_date)
    total = 0
    for invoice in invoice_set:
        for sale in invoice.salesrecord_set.all():
            total += getattr(self, variable)
    return round(total)

Where variable is submitted as a string that represents one of my model methods:

@property
def total_sale(self):
    return self.sales_price * self.sales_qty

But my effort doesn't work:

def total_sales(self):
    return self.retrieve_data(variable="total_sale")

It simply says:

'SalesSummaryView' object has no attribute 'total_sale'

Evidently, I am misunderstanding the usage. Can someone help me figure out a way to accomplish this goal?


Solution

  • Got it! I was calling getattr() on the view, rather than the model. Instead of using self, I needed to submit the sale object.

    for invoice in invoice_set:
        for sale in invoice.salesrecord_set.all():
            total += getattr(sale, variable)