Monthly total function for different object properties
I have the following function that calculates the total widgets manufactured each month for the given year:
def get_monthly_totals(year):
queryset = Widget.objects.filter(manufactured__year=year)
totals = [0] * 12
for widget in queryset:
totals[widget.manufactured.month -1] += 1
return totals
First it gets all the widget objects for the given year, then tallies up the totals for each month.
Now the widget object also has a sold property (also a datetime type). I would like to pass a parameter to the above function to tell it to calculate either the sold monthly totals or manufactured monthly totals. I could write another function that did the same thing and replace manufactured with sold, but that seems to go against the DRY principle. What's the most pythonic approach of doing 开发者_StackOverflow社区this?
One option is to use getattr()
:
def get_monthly_totals(year, attr):
queryset = Widget.objects.filter(**{attr + "__year": year})
totals = [0] * 12
for widget in queryset:
totals[getattr(widget, attr).month -1] += 1
return totals
totals_manufactured = gtotalset_monthly_totals(year, "manufactured")
totals_sold = get_monthly_totals(year, "sold")
精彩评论