Reputation: 1637
I am using peewee
module for managing data in Sqlite
database. My use case scenarios is that I will be creating a database with certain fields. I also need to add columns into the existing database at certain time. Below is my code that is supposed to work as expected:
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()
After adding a new column address
for which null=True
, I am doing some insertion into the altered database. I am expected to see Address data into address
field, but I am not getting any of these data. Instead it's NULL
. My code should have worked fine, but its not working as expected. Whats the problem here?
Upvotes: 0
Views: 732
Reputation: 26235
In your insertAfterAlteringDatabase
you will need to add the new field to the model. The migrator added the column to the database table, but it did not add the field to the model class. To do that, you can:
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.
Upvotes: 2