Python peewee无法在插入新列后插入数据
我正在使用Python peewee无法在插入新列后插入数据,python,sqlite,peewee,Python,Sqlite,Peewee,我正在使用peewee模块来管理Sqlite数据库中的数据。我的用例场景是,我将创建一个带有特定字段的数据库。我还需要在特定时间向现有数据库中添加列。下面是我的代码,它应该按预期工作: from peewee import * import os from playhouse.migrate import * my_db = SqliteDatabase('my_database.db') migrator = SqliteMigrator(my_db) class FirstTable(M
peewee
模块来管理Sqlite
数据库中的数据。我的用例场景是,我将创建一个带有特定字段的数据库。我还需要在特定时间向现有数据库中添加列。下面是我的代码,它应该按预期工作:
from peewee import *
import os
from playhouse.migrate import *
my_db = SqliteDatabase('my_database.db')
migrator = SqliteMigrator(my_db)
class FirstTable(Model):
first_name = CharField(null=True)
last_name = CharField(null=True)
class Meta:
database = my_db
class Checkit:
def __init__(self):
self.db = my_db
self.migrator = migrator
def makeDatabse(self):
if os.path.exists("my_database.db"):
print "File Exists remove it"
os.remove("my_database.db")
try:
self.db.connect()
self.db.create_tables([FirstTable,])
except OperationalError:
print "Table Exists"
def insertDatas(self):
with self.db.atomic():
for i in range(10):
first_name_ = "Hello " + str(i)
last_name_ = "World " + str(i)
db_ = FirstTable(first_name=first_name_, last_name = last_name_)
db_.save()
def alterDatabase(self, columns):
with self.db.transaction():
columnField = CharField(null=True)
for column in columns:
migrate(migrator.add_column("firsttable", column, columnField))
def insertAfterAlteringDatabase(self):
with self.db.atomic():
for i in range(20,30):
first_name_ = "Hello " + str(i)
last_name_ = "World " + str(i)
address_ = "Address " + str(i)
db_ = FirstTable(first_name=first_name_, last_name = last_name_, address=address_)
db_.save()
ch = Checkit()
ch.makeDatabse()
ch.insertDatas()
ch.alterDatabase(["address"])
ch.insertAfterAlteringDatabase()
在添加了一个新的列
address
,该列的null=True
之后,我将插入到修改过的数据库中。我希望在Address
字段中看到地址数据,但我没有得到任何这些数据。相反,它是NULL
。我的代码应该工作得很好,但它没有按预期工作。这里有什么问题?在您的插入中,在更改数据库之后,您需要将新字段添加到模型中。迁移器将列添加到数据库表中,但没有将字段添加到模型类中。为此,您可以:
def alterDatabase(self, columns):
with self.db.transaction():
columnField = CharField(null=True)
for column in columns:
migrate(migrator.add_column("firsttable", column, columnField))
columnField.add_to_class(FirstTable, column) # Add the field to the model.
这似乎奏效了。我认为添加代码的缩进是错误的。它不应该是内环吗?谢谢