Created
March 13, 2019 21:21
-
-
Save hvgab/168003a4f073dc736bd9bbe8774b930a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from django.db.models import Count | |
class Game(models.Model): | |
"""A game to be played and/or owned""" | |
name = models.CharField(max_length=255) | |
class Player(models.Model): | |
"""Someone who plays games""" | |
name = models.CharField(max_length=255) | |
games = models.ManyToManyField(Game) | |
@cached_property | |
def win_count(self): | |
return self.play_set.filter(winner=self).count() | |
@cached_property | |
def play_count(self): | |
return self.play_set.count() | |
@cached_property | |
def game_count(self): | |
return self.games.count() | |
@property | |
def winrate(self): | |
try: | |
return self.win_count / self.play_count | |
except: | |
# If player has 0 as play_count | |
return 0 | |
def get_most_played_game(self): | |
game_total = self.play_set.values('game').annotate( | |
total=Count('game')).order_by('-total').first() | |
game = Game.objects.get(id=game_total['game']) | |
return game | |
def get_most_played_player(self, game: Game = None): | |
# Help | |
pass | |
class Play(models.Model): | |
"""Players have played a game""" | |
name = models.CharField(max_length=50, null=True, blank=True) | |
description = models.TextField(max_length=250, null=True, blank=True) | |
date = models.DateField( | |
default=timezone.now, help_text='When was the game played?') | |
game = models.ForeignKey( | |
Game, | |
on_delete=models.SET_NULL, | |
null=True, | |
help_text='What game was played?') | |
players = models.ManyToManyField(Player, help_text='Who was playing?') | |
winner = models.ForeignKey( | |
Player, on_delete=models.SET_NULL, null=True, related_name='winner') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment