Browse code

correction cleanup

devnewton authored on 02/01/2012 at 23:14:31
Showing 2 changed files
... ...
@@ -1,4 +1,5 @@
1 1
 from django.db import models
2
+from django.conf import settings
2 3
 
3 4
 class Game(models.Model):
4 5
     slug = models.SlugField(max_length=80, unique=True)
... ...
@@ -21,6 +22,10 @@ class Level(models.Model):
21 21
         return ('scorekeeper.views.level_detail', [str(self.slug)])
22 22
     def sorted_scores(self):
23 23
         return self.score_set.all().order_by('-score')
24
+    def cleanup(self):
25
+        if self.score_set.count() > settings.SCORESERVER_MAX_SCORE_TO_KEEP:
26
+            for scoreToDelete in self.score_set.all().order_by('-score')[settings.SCORESERVER_MAX_SCORE_TO_KEEP:]:
27
+                scoreToDelete.delete()
24 28
 
25 29
 class Player(models.Model):
26 30
     slug = models.SlugField(max_length=80, unique=True)
... ...
@@ -32,6 +37,10 @@ class Player(models.Model):
32 32
         return self.slug
33 33
     def sorted_scores(self):
34 34
         return self.score_set.all().order_by('-level__name', '-score')
35
+    @staticmethod
36
+    def cleanup():
37
+        for player in Player.objects.annotate(num_scores = models.Count('score')).filter(num_scores = 0):
38
+            player.delete()
35 39
 
36 40
 class Score(models.Model):
37 41
     player = models.ForeignKey(Player)
... ...
@@ -2,7 +2,6 @@ from django.http import HttpResponse
2 2
 from django.template import RequestContext, loader
3 3
 from django.views.generic import list_detail
4 4
 from scorekeeper.models import Game, Level, Player, Score
5
-from django.conf import settings
6 5
 
7 6
 def index(request):
8 7
     games = Game.objects.all().order_by('-name')
... ...
@@ -22,6 +21,7 @@ def player_detail(request, player_slug):
22 22
     return list_detail.object_detail( request, queryset= Player.objects.all(), slug=player_slug, slug_field='slug', template_name='scorekeeper/templates/player_detail.html'  )
23 23
 
24 24
 def score(request):
25
+    #create or update score
25 26
     level = Level.objects.get(slug=request.REQUEST['level'])
26 27
     player, isNewPlayer = Player.objects.get_or_create(slug=request.REQUEST['player'], defaults={'secret':request.REQUEST['secret']})
27 28
     if not isNewPlayer and player.secret != request.REQUEST['secret']:
... ...
@@ -30,7 +30,7 @@ def score(request):
30 30
     if not isNewScore:
31 31
         score.score = request.REQUEST['score']
32 32
         score.save()
33
-    if level.score_set.count() > settings.SCORESERVER_MAX_SCORE_TO_KEEP:
34
-        for scoreToDelete in level.score_set.all().order_by('-score')[settings.SCORESERVER_MAX_SCORE_TO_KEEP:]:
35
-            scoreToDelete.delete()
33
+    #cleanup
34
+    level.cleanup()
35
+    Player.cleanup()
36 36
     return HttpResponse("score saved")