django - Migrating from abstract model to proxy models -
right now, have abstract model several models inherits fields. have discovered power of proxy models, , want implement them app. picture now:
class basemodel(models.model): field_1 = models.charfield(max_length=10) field_2 = models.charfield(max_length=10) field_3 = models.charfield(max_length=10) class meta: abstract = true class model1(basemodel): pass def __unicode__(self): return self.field_1 class model2(basemodel): pass def __unicode__(self): return self.field_1
and want:
class basemodel(models.model): field_1 = models.charfield(max_length=10) field_2 = models.charfield(max_length=10) field_3 = models.charfield(max_length=10) class model1(basemodel): pass class meta: proxy = true def __unicode__(self): return self.field_1 class model2(basemodel): pass class meta: proxy = true def __unicode__(self): return self.field_1
the problem when remove "abstract = true" sentence. when try migrate, warning:
you trying add non-nullable field 'basemodel_ptr' model1 without default; can't (the database needs populate existing rows).
ok, got it. read "ptr" pointer parent model, basemodel, don't have basemodel, , cannot until migrate. how can fix this??
the migrations not trivial.
currently, database has 2 tables:
yourapp_model1
yourapp_model2
both have same columns use different sequences meaning primary keys clash: both of tables start counting ids (aka pks) 1 onwards. there chance there instance of model1
pk=1
instance of model2
pk=1
, not same.
this point of having abstract model , concrete implementations: share django code (business logic) while separating data in db. example, because semantically different (different types).
the point of proxy models exact opposite: while data located in 1 table in db, proxy models allow implement different behaviour based on same db data.
if migrating abstract models proxy models means once considered different types become same types (from database point of view). mentioned @ beginning, have move data several tables 1 , regenerate ids @ least part of it. meaning also, part of resources using these urls change/cease exist/point different resource.
unless can start scratch (no live data have support) should appreciate magnitude of change.
should not have need support live data:
- drop database
- recreate database
- remove migration files
- recreate migration files scratch
- call migrate
data migration of live data:
note there other ways this. search "django data migration".
- create new model structure new names (no collisions)
- makemigrations pick new model structure , create new , empty tables in database leaving old tables , data untouched
- create management command reads in old model instances , copies them new tables
- once command has been run on production can deprecate old models , remove them while making sure depending on them using new tables
Comments
Post a Comment