import os
import datetime
import peewee as pw
from werkzeug.security import generate_password_hash, check_password_hash
database = pw.SqliteDatabase('db.sqlite')
class Model(pw.Model):
class Meta:
database = database
class User(Model):
username = pw.CharField()
password_hash = pw.CharField()
@property
def password(self):
raise AttributeError('password is not readable')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def __str__(self):
return '<User %r>' %self.username
class Category(Model):
tag = pw.CharField()
count = pw.IntegerField(default=0)
def __str__(self):
return '<Category %r>' %self.tag
class Post(Model):
title = pw.CharField()
body = pw.TextField()
summary = pw.CharField()
category = pw.ForeignKeyField(Category, backref='posts')
timestamp = pw.DateTimeField(default=datetime.datetime.now)
def __str__(self):
return '<Post %r>' %self.title
if __name__ == "__main__":
if not os.path.exists('db.sqlite'):
User.create_table()
Post.create_table()
Category.create_table()
categoryC = Category.create(tag='C')
categoryPy = Category.create(tag='Py')
Post.create(category=categoryC, title='learn c', body='learn c hardly', summary='').save()
Post.create(category=categoryPy, title='learn py', body='learn py hardly', summary='').save()
Post.create(category=categoryPy, title='learn flask', body='learn flask hardly', summary='').save()
for category in Category.select():
print(category)
for post in category.posts:
print(' ', post)
1
XIVN1987 OP 网上的代码是用__repr__,,我试了下不行,,可能新版本改用__str__了
|
2
rogwan 2018-11-22 13:44:24 +08:00 via iPhone
楼主对比过 sqlalchemy 没,用起来有什么差别吗?
|
3
XIVN1987 OP |
4
rogwan 2018-11-22 13:56:21 +08:00 via iPhone
@XIVN1987 反正从来不用外键,觉得 sqlalchemy 有些函数功能还是蛮强大的,没用过 pw,没法对比。
|
5
keven2000 2018-11-22 21:29:36 +08:00
sqlalchemy 基本对付大部分场景了,可 raw sql、sql expression、orm
|