插入新列后,peewee 无法插入数据

peewee cannot insert data after new column insertion

我正在使用 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()

在为 null=True 添加新列 address 后,我正在向更改后的数据库中插入一些内容。我应该在 address 字段中看到地址数据,但我没有得到任何这些数据。相反,它是 NULL。我的代码应该工作正常,但它没有按预期工作。这里有什么问题?

在您的 insertAfterAlteringDatabase 中,您需要将新字段添加到模型中。迁移器将 添加到数据库 table,但未将 字段 添加到模型 class。为此,您可以:

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.