更新现有的表/模型列/字段?

4
如何在 PeeWee 中更新表格的列和列数据类型?
我已经从我的模型创建了数据库中的表格Person。但是,我现在向模型添加了一些新字段并更改了某些现有字段/列的类型。
以下内容不会更新表格结构:
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个回答

4
根据文档:http://docs.peewee-orm.com/en/latest/peewee/example.html?highlight=alter 添加表格之后,如果需要添加字段,则需要删除该表并重新创建它或手动使用 ALTER TABLE 查询添加列。或者,您可以使用模式迁移扩展来使用 Python 修改您的数据库模式。
根据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'),
)

还有许多其他操作是可能的。

因此,首先需要修改表模式,然后才能更新模型以反映这些更改。


“更改了某些现有字段/列的类型”是其中一个问题[我现在也遇到的问题],但我看不到任何允许更改现有字段的内容。在最初的示例中,@sazr正在更改“is_relative”。 - MountainAsh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接