-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpeewee_ex.py
More file actions
82 lines (60 loc) · 1.64 KB
/
Copy pathpeewee_ex.py
File metadata and controls
82 lines (60 loc) · 1.64 KB
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
import datetime
from peewee import (
SqliteDatabase, Model, CharField, ForeignKeyField, TextField, DateTimeField, BooleanField
)
db = SqliteDatabase('peewee.db')
class BaseModel(Model):
class Meta:
database = db
def __str__(self):
return "{name}<{pk}>".format(name=self.__class__.__name__, pk=super().__str__())
class User(BaseModel):
username = CharField(unique=True)
password = CharField(max_length=120)
class Task(BaseModel):
user = ForeignKeyField(User, backref='task')
message = TextField()
created_date = DateTimeField(default=datetime.datetime.now)
is_published = BooleanField(default=True)
def initialise_db():
"""Initialise database"""
_user1, _ = User.get_or_create(
username="ozcan",
password="123"
)
Task.get_or_create(
user=_user1,
message="Hello World"
)
Task.get_or_create(
user=_user1,
message="How are you?"
)
_user2, _ = User.get_or_create(
username="naczo",
password="321"
)
Task.create(
user=_user2,
message="Hello again"
)
if __name__ == '__main__':
db.connect()
db.create_tables([User, Task])
initialise_db()
user = User.get_by_id(pk=1)
print(
user.username,
user.password,
user.task.count(),
)
task = Task.get(Task.user == user)
print(task)
try:
task = Task.get(Task.message == "Hello World?")
print(task)
except Task.DoesNotExist:
print("Model does not exists")
tasks = Task.select().filter(Task.message.contains('Hello'))
for task in tasks:
print(task)