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

2024-10-01 17:38:32 发布

您现在位置:Python中文网/ 问答频道 /正文

如何更新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)

Tags: toname模型selfdbistypeupdate
1条回答
网友
1楼 · 发布于 2024-10-01 17:38:32

来自文档: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.

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'),
)

还有很多其他的手术是可能的。在

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

相关问题 更多 >

    热门问题