Add word drawing support

This commit is contained in:
Gergely Polonkai 2015-11-26 14:51:04 +01:00
parent 955cace9bd
commit 0c16d9a73b
4 changed files with 66 additions and 2 deletions

View File

@ -24,8 +24,31 @@ def _current_word(self):
return None
def _draw_word(self):
if self.current_word() is not None:
return self.current_word()
from .models import Word, Draw
# Find all words
# Exclude all words that has an accepted draw for this user
# Choose a random one
# If there are no more words, return None
word = Word.objects \
.exclude(draws__accepted=True, draws__user=self) \
.order_by('?') \
.first()
if word is None:
return None
Draw.objects.create(user=self, word=word, accepted=None)
return word
class WordsConfig(AppConfig):
name = 'words'
def ready(self):
User.current_word = _current_word
User.draw_word = _draw_word

View File

@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('words', '0002_draw_work'),
]
operations = [
migrations.AlterField(
model_name='draw',
name='word',
field=models.ForeignKey(related_name='draws', to='words.Word'),
),
]

View File

@ -50,7 +50,7 @@ class WordTranslation(models.Model):
class Draw(models.Model):
user = models.ForeignKey(User)
word = models.ForeignKey(Word)
word = models.ForeignKey(Word, related_name='draws')
accepted = models.NullBooleanField()
timestamp = models.DateTimeField(default=timezone.now)

View File

@ -3,7 +3,7 @@ from django.core.exceptions import ValidationError
from django.utils.translation import activate
from django.test import TestCase
from .models import Word, WordTranslation, Draw
from .models import Word, WordTranslation, Draw, Work
class WordTest(TestCase):
def setUp(self):
@ -71,3 +71,25 @@ class DrawTest(TestCase):
draw.accepted = True
draw.save()
self.assertEquals(self.word, self.user.current_word())
def test_draw_word(self):
draw = Draw.objects.create(user=self.user,
word=self.word,
accepted=None)
self.assertEquals(self.word, self.user.draw_word())
draw.accepted = True
draw.save()
Work.objects.create(draw=draw)
word2 = Word.objects.create()
self.assertEquals(word2, self.user.draw_word())
draw = Draw.objects.get(user=self.user, word=word2)
self.assertIsNotNone(draw)
self.assertIsNone(draw.accepted)
draw.accepted = True
draw.save()
Work.objects.create(draw=draw)
self.assertIsNone(self.user.draw_word())