-
-
Notifications
You must be signed in to change notification settings - Fork 302
Description
When you create an instance of a polymorphic model in a (data) migration, the polymorphic_ctype_id will be left null. The reason is that this field is set in PolymorphicModel.pre_save_polymorphic which is called from save. However, save is never called when running migrations, because in migrations we don't use the actual model classes but the 'historical models' maintained by the migrations engine. As the documentation says: "Because it’s impossible to serialize arbitrary Python code, these historical models will not have any custom methods that you have defined. " This includes the custom save (and pre_save_polymorphic) methods.
The result is that naively creating a polymorphic model instance from migrations will create instances without a valid polymorphic_ctype FK which will cause problems down the road when you try to access these instances. And this is pretty evil as it won't necessarily be caught by tests.
This has been reported before (see #197 ), but closed due to a misunderstanding probably with a reference to the documentation explaining how to migrate existing objects. But this is a distinct problem.
Now besides this being a documentation problem (i.e. undocumented), also raises the question if polymorphic_ctype should be non-nullable. (I don't know what's the decision behind allowing null values, maybe there is a good reason, but getting any instance with a null polymorphic_ctype will fail with an exception which hints that it shouldn't be allowed.)
Setting polymorphic_ctype non-nullable would at least prevent creating invalid data. As far as I can see, the only solution is to manually set the polymorphic_ctype as mentioned in the documentation for migrating existing models. (But note, that the documentation is wrong about how to do that. I'll open another issue for that.)