2017-06-24 17 views
0

テーブルの列と列のデータ型を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) 

答えて

0

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

そして、多くの他の操作ができますたくさん。

まず、テーブルスキーマを変更してから、その変更を反映するようにモデルを更新する必要があります。

関連する問題