coleifer / peewee

a small, expressive orm -- supports postgresql, mysql, sqlite and cockroachdb
http://docs.peewee-orm.com/
MIT License
11.06k stars 1.37k forks source link

How do I add a ForeignKeyField to a model that is not yet defined? #2880

Closed stenci closed 4 months ago

stenci commented 4 months ago

Hi All,

I am redesigning a database and I need to add a foreign field to a table. I have used this line after the definition of all the models, and it works well:

playhouse.migrate.migrate(migrator.add_column('cncprogramsheet', 'inventory_sheet_id', 
                            peewee.ForeignKeyField(InventorySheet, 
                                      InventorySheet.id,
                                      backref='cnc_program_sheets', 
                                      null=True)))

As the changes to the database are increasing, I would like to move the migration up in the code, before the definition of the models. The previous line fails because InventorySheet is not defined yet, so I tried with this:

playhouse.migrate.migrate(migrator.add_column('cncprogramsheet', 'inventory_sheet_id', 
                            peewee.DeferredForeignKey('InventorySheet', 
                                      to_field='id', 
                                      backref='cnc_program_sheets', 
                                      null=True)))

I thought the two lines were equivalent, but I am getting this error message:

AttributeError: 'DeferredForeignKey' object has no attribute 'model'

Why am I getting this error? Is my approach completely wrong?

coleifer commented 4 months ago

Yeah, you can't use a deferred foreign key in a migration.