Hip*_*ppo 2 python oop peewee flask-peewee
我正在尝试设置一组可重用的数据模型,可以将其包含在多个应用程序中,如下所示(我在这里使用用户作为示例,但实际的数据模型是库的 peewee 后端Authlib):
# mixins.py
class UserMixin(peewee.Model):
    username = peewee.CharField()
    password = peewee.CharField()
    def set_password(self):
        # do stuff
    ...
创建 mixin 后,我应该能够像这样导入它,仅定义附加字段(默认值已经来自 mixin)
# models.py
db = peewee.SqliteDatabase(config.get('DATABASE_FILE'))
class BaseModel(peewee.model):
    class Meta:
        database = db
class User(BaseModel, UserMixin):
    email = peewee.CharField()
    ...
我见过人们用 这样做SQLAlchemy,但是当我将这个策略与 peewee 一起使用时,它似乎没有正确保存字段:
UserMixin继承自peewee.Model,它会说“无法解析导入层次结构”(可能是因为我们peewee.Model多次导入)UserMixin只是一个object, then peewee 似乎没有正确处理它的字段:它们最终都作为未绑定的实例并且不会保存在数据库中。我的问题:是否有一种“官方方式”来创建带有peewee字段的可重用模型混合?
我见过其他项目(例如flask-login)使用 mixins,但这些通常是像本示例中那样的附加函数set_password,而不是定义字段本身的函数。
我有一些潜在的替代解决方案,例如
.Meta.database为每个models.py条目单独覆盖它们models.pyimport直接进行复制。但可能有一些更干净的方法来做到这一点?
这是一个简单的例子:
from peewee import *
db = SqliteDatabase(':memory:')
class Base(Model):
    class Meta:
        database = db
class UserModelMixin(Model):
    username = TextField()
class User(UserModelMixin, Base):
    pass
print(User._meta.fields)
#{'id': <AutoField: User.id>, 'username': <TextField: User.username>}
我认为问题出在你的混入的顺序上。
| 归档时间: | 
 | 
| 查看次数: | 384 次 | 
| 最近记录: |