【发布时间】:2021-06-29 20:12:50
【问题描述】:
我是 peewee 的新手,我对迁移非常困惑。我尝试了官方文档中的例子,得到的结果如下:
from playhouse.migrate import *
from peewee import *
my_db = SqliteDatabase('my_database.db')
migrator = SqliteMigrator(my_db)
from peewee import *
database = SqliteDatabase('my_database.db')
class BaseModel(Model):
class Meta:
database = database
class Product(BaseModel):
name = TextField()
class Meta:
table_name = 'product'
with my_db:
my_db.create_tables([Product,])
Product.create(name = 'Big Peach')
price_field = IntegerField(default=0)
migrate(migrator.add_column('product', 'price', price_field))
db = migrator.database
columns = db.get_columns('product')
print(columns)
这是我得到的并添加了“价格”字段,表明migrated ()做得很好:
[ColumnMetadata(name='id', data_type='INTEGER', null=False, primary_key=True, table='product', default=None), ColumnMetadata(name='name', data_type='TEXT', null=False, primary_key=False, table='product', default=None), ColumnMetadata(name='price', data_type='INTEGER', null=False, primary_key=False, table='product', default=None)]
现在的问题是当我打电话给Product.price时,
query = Product.get(Product.name == 'Big Peach')
print(query.price)
出现如下结果:
“产品”对象没有属性“价格”
我在命令行中尝试了另一种方法:
python -m pwiz -e sqlite my_database.db
我知道了:
from peewee import *
database = SqliteDatabase('my_database.db')
class UnknownField(object):
def __init__(self, *_, **__): pass
class BaseModel(Model):
class Meta:
database = database
class Product(BaseModel):
name = CharField()
price = IntegerField()
class Meta:
table_name = 'product'
我可以使用这些来替换以前的模型,但不需要migrate()。
所以,我的困惑是如何在一个.py 文件中调用使用migrate() 添加的新字段。
【问题讨论】: