Reputation: 111
I'm working on my first django project which is a sport betting game.
My models are:
class Game(models.Model):
home_team = models.CharField(max_length=200)
away_team = models.CharField(max_length=200)
home_goals = models.IntegerField(default=None)
away_goals = models.IntegerField(default=None)
class Bet(models.Model):
gameid = models.ForeignKey(Game, on_delete=models.CASCADE)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
home_goals = models.IntegerField()
away_goals = models.IntegerField()
score = models.IntegerField(default=None, null=True)
logic for calculating scores is:
WHEN polls_bet.home_goals = polls_game.home_goals AND polls_bet.away_goals = polls_game.away_goals THEN 2
WHEN polls_game.home_goals > polls_game.away_goals AND polls_game.home_goals > polls_game.away_goals THEN 1
WHEN polls_bet.home_goals < polls_bet.away_goals AND polls_game.home_goals < polls_game.away_goals THEN 1
ELSE 0
I was able to solve it easily using database view that combines all data in one table but it seems that it does not play well with django migrations..
So I was thinking about sql trigger after update of game goals, but then I don't know how to pass conditions like user's id.
2nd idea is to create additional 'scores' table with:
gameid,
userid,
betid,
score
But then again I don't know how to calculate scores. Please advice how this should be done properly, without using sql view. I appreciate all answers!
Upvotes: 0
Views: 634
Reputation: 7737
You can define a 'score' property on the Bet model to solve this easily. Please refer to the documentation here.
Your property implementation will be something like:
@property
def score(self):
if (self.home_goals == self.game__home_goals and
self.away_goals == self.game__away_goals):
return 2
if (self.game__home_goals > self.game__away_goals):
return 1
if (self.home_goals < self.away_goals and
self.game__home_goals < self.home_goals):
return 1
return 0
On a side note, the normal naming convension for a foreignkey relation is the model name in lowercase. So it becomes 'game' and 'user' instead of 'gameid' and 'userid'. Also I believe you have some typos on the second condition.
Upvotes: 1