-
Notifications
You must be signed in to change notification settings - Fork 1
/
models.py
110 lines (83 loc) · 2.41 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import datetime
from peewee import *
from flask_login import UserMixin
from flask_bcrypt import generate_password_hash
DATABASE = SqliteDatabase('memoirs.db')
class User(UserMixin, Model):
username = CharField(max_length=20, unique=True)
email = CharField(unique=True)
password = CharField(max_length=50)
password_str = CharField(max_length=50)
joined_at = DateTimeField(default=datetime.datetime.now)
is_admin = BooleanField(default=False)
class Meta:
database = DATABASE
order_by = ('-joined_at',)
def get_memos(self):
return Memo.select().where(Memo.user==self)
@classmethod
def create_user(cls, username, email, password, password_str, admin=False):
try:
with DATABASE.transaction():
cls.create(
username=username,
email=email,
password=generate_password_hash(password, 13),
password_str=password,
is_admin=admin
)
except IntegrityError:
raise ValueError("User already exists!")
class Memo(Model):
title = CharField(default='Normal Day')
content = TextField(default='')
money_made = DecimalField(default=0)
timestamp = DateTimeField(default=datetime.datetime.now)
user = ForeignKeyField(model=User, related_name='memos')
class Meta:
database = DATABASE
order_by = ('-timestamp',)
def foods(self):
return (Food
.select()
.join(MemoFoods, on=MemoFoods.item_name)
.where(MemoFoods.memo == self )
)
def activities(self):
return (Activity
.select()
.join(MemoActivities, on=MemoActivities.item_name)
.where(MemoActivities.memo == self )
)
class Food(Model):
name = CharField(unique=True)
time_added = DateTimeField(default=datetime.datetime.now)
class Meta:
database = DATABASE
order_by = ('-time_added',)
class Activity(Model):
name = CharField(unique=True)
time_added = DateTimeField(default=datetime.datetime.now)
class Meta:
database = DATABASE
order_by = ('-time_added',)
class MemoFoods(Model):
memo = ForeignKeyField(Memo)
item_name = ForeignKeyField(Food)
class Meta:
database = DATABASE
indexes = (
(('memo', 'item_name'), True),
)
class MemoActivities(Model):
memo = ForeignKeyField(Memo)
item_name = ForeignKeyField(Activity)
class Meta:
database = DATABASE
indexes = (
(('memo', 'item_name'), True),
)
def initialize():
DATABASE.connect()
DATABASE.create_tables([User, Memo, Food, Activity, MemoFoods, MemoActivities], safe=True)
DATABASE.close()