Update existing table/model column/fields?

好久不见. 提交于 2019-12-11 08:07:26

问题


How can I update a tables columns and column data types in PeeWee?

I have already created the table Person in the database from my model. But I've now added some new fields to the model and changed the type of certain existing fields/columns.

The following doesn't update the table structure:

psql_db = PostgresqlExtDatabase(
    'MyDB',
    user='foo',
    password='bar',  
    host='', 
    port='5432',
    register_hstore=False
)

class PsqlModel(Model):
    """A base model that will use our Postgresql database"""
    class Meta:
        database = psql_db


class Person(PsqlModel):
    name = CharField()
    birthday = DateField()          # New field
    is_relative = BooleanField()    # Field type changed from varchar to bool

    def __str__(self):
        return '%s, %s, %s' % (self.name, self.birthday, self.is_relative)


psql_db.connect()

# is there a function to update/change the models table columns??
psql_db.create_tables([Person], True)  # Hoping an update of the table columns occurs

# Error because no column birthday and incorrect type for is_relative
grandma_glen = Person.create(name='Glen', birthday=date(1966,1,12), is_relative=True)

回答1:


From the documentation: http://docs.peewee-orm.com/en/latest/peewee/example.html?highlight=alter

Adding fields after the table has been created will required you to either drop the table and re-create it or manually add the columns using an ALTER TABLE query.

Alternatively, you can use the schema migrations extension to alter your database schema using Python.

From http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#migrate:

# Postgres example:
my_db = PostgresqlDatabase(...)
migrator = PostgresqlMigrator(my_db)
title_field = CharField(default='')
status_field = IntegerField(null=True)

migrate(
    migrator.add_column('some_table', 'title', title_field),
    migrator.rename_column('some_table', 'pub_date', 'publish_date'),
    migrator.add_column('some_table', 'status', status_field),
    migrator.drop_column('some_table', 'old_column'),
)

And a lot many other operations are possible.

So, first you will need to alter the table schema, and then, you can update your model to reflect those changes.



来源:https://stackoverflow.com/questions/44732427/update-existing-table-model-column-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!