1👍
✅
Best way would be not to create MonthlyBets at all. You can get monthly records by calculation from your Bet model like in Section 2(renamed Bet to Tip).
Section 1
If you insist on creating MonthlyBets model, you can overwrite Django Admin save method. Or listen for post_save signal of Bet model. If new Bet object is created, update MonthlyBets.
Section 2
It is not very straightforward code, but it does calculate Yield
, Count
and Win Ratio
for each month for Tip model.
for date in Tip.objects.datetimes('date_game', 'month', order='DESC'):
date_filter['date_game__month'] = date.month
date_filter['date_game__year'] = date.year
date_yield, date_count, date_win = get_yield(date_filter)
month_list.append({"month": date, "yield": date_yield,
"count": date_count,
"win": date_win})
And something like this in utils.py
or wherever you keep your logic.
from django.db.models import Sum, F
from django.db import models as db_models
def get_yield(filter={}):
"""
@kwargs filter options = date_game__month=month, date_game__year=year, sport__name=sport, etc
:return: yield, all_tips_count, win_tips_count
http://stackoverflow.com/questions/12165636/django-aggregation-summation-of-multiplication-of-two-fields
"""
win_sum = Tip.objects.filter(result=Tip.WIN, **filter).aggregate(total=Sum(F('odds')*F('stake'),
output_field=db_models.DecimalField()))['total']
if win_sum==None:
win_sum=0
stake_sum = Tip.objects.filter(result__in=[Tip.WIN, Tip.LOST], **filter).aggregate(total=Sum('stake'))['total']
if stake_sum==None:
return 0, Tip.objects.filter(result__in=[Tip.WIN, Tip.LOST], **filter).count(),\
Tip.objects.filter(result__in=[Tip.WIN], **filter).count()
return (win_sum-stake_sum)/stake_sum * 100,\
Tip.objects.filter(result__in=[Tip.WIN, Tip.LOST], **filter).count(),\
Tip.objects.filter(result__in=[Tip.WIN], **filter).count()
Source:stackexchange.com