-
Notifications
You must be signed in to change notification settings - Fork 1
/
models.py
93 lines (78 loc) · 2.26 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# coding: utf-8
from peewee import *
db = SqliteDatabase('database.db')
class BaseModel(Model):
"""
Base class for models.
"""
class Meta:
database = db
class User(BaseModel):
"""
User model for minimalists.
"""
username = CharField()
hashsum = CharField()
class GameSession(BaseModel):
"""
Game session model.
"""
is_active = BooleanField(default=False)
gid = IntegerField() # на самом деле, айдишник уже есть в модели по умолчанию
owner = ForeignKeyField(User, null=True)
def get_users(self):
"""
Returns users who are involved in this game session.
"""
return (
User.select()
.join(SessionUsers)
.join(GameSession)
.where(SessionUsers.session == self)
)
class SessionUsers(BaseModel):
"""
Implementation for any-to-many relation of GameSession and User models.
"""
session = ForeignKeyField(GameSession, null=True)
user = ForeignKeyField(User, null=True)
correct_answers = IntegerField()
class Question(BaseModel):
"""Model for questions"""
id = IntegerField(primary_key=True) # айдишник уже есть в модели по умолчанию
type = CharField()
description = CharField()
question = CharField()
correct_answer = CharField()
def check_answer(self, user_answer):
"""Returns True if user answer is correct, otherwise False"""
return user_answer == self.correct_answer
def serialize_to_dict(self, with_answer=False):
"""Serializes this model into dict"""
result = {
'id': self.id,
'type': self.type,
'description': self.description,
'question': self.question,
}
if with_answer:
result['correct_answer'] = self.correct_answer
return result
@classmethod
def serialize_all(cls, with_answers=False):
"""Serializes all questions into list of dicts"""
result = []
for question in Question.select():
result.append(question.serialize_to_dict(with_answer=with_answers))
return result
if __name__ == '__main__':
'''
небольшие проверочки
'''
u = User.create(username='yoba', hashsum='123')
u2 = User.create(username='yobayoba', hashsum='456')
gs = GameSession.create(gid=30)
su = SessionUsers.create(session=gs, user=u)
su2 = SessionUsers.create(session=gs, user=u2)
for user in gs.get_users():
print(user.username)