更新现有的表/模型列/字段? [英] Update existing table/model column/fields?

查看:58
本文介绍了更新现有的表/模型列/字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更新 PeeWee?

我已经从我的模型在数据库中创建了表 Person.但我现在向模型添加了一些新字段并更改了某些现有字段/列的类型.

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.

以下不会更新表结构:

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)

推荐答案

来自文档:http://docs.peewee-orm.com/en/latest/peewee/example.html?highlight=alter

在表创建后添加字段需要您删除表并重新创建它或手动添加列使用 ALTER TABLE 查询.

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.

或者,您可以使用架构迁移扩展来更改使用 Python 的数据库架构.

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

还有很多其他的操作是可能的.

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.

这篇关于更新现有的表/模型列/字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆