M
M
Megadeth772019-05-31 17:16:11
Django
Megadeth77, 2019-05-31 17:16:11

How to organize migration in Django for two related models with automatic substitution of default field values?

Consider the example of Django, but the question is about any ORM. Suppose there is a production base with some data in it. it is necessary to carry out migration in the following tricky case.
There is a model, let's say Model, it has foregin keys for other models.

class ModelA: ...
class ModelX: ...

class Model:
  a = models.ForeignKey(ModelA, default=A)
  x = models.ForeignKey(ModelX, default=X)

And then at one fine moment we create another model (ModelY) to which Model should refer. And when creating a Model, the object must have a reference to some default ModelY object, which obviously does not exist yet!
class ModelY: ...
class Model:
  y = models.ForeignKey(ModelY, default=??????)

Those. the sequence during migration should be as follows:
-Create a ModelY table -Create
a default object in this table, write its id
somewhere -Create a new field in the Model table, and take the default value from the previous paragraph
And I would like to automate all this, of course, so that no Do not roll migrations with handles, then take the value from the database and put it in the code. And I would also like to do it all in one sitting, i.e. define both the new model and the new field in the old model at once, and then roll the migration at once and make everything work.
Is there any best prectice for such a case? Or at least what keywords to google for?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
marazmiki, 2019-05-31
@Megadeth77

The scenario for dzhanga I would suggest is this:

  1. Create a ModelY model, generate and apply the appropriate migration.
    As for best practices, from experience I would advise the following:
    • No need to try to minimize the number of migrations or shove everything into one. On the contrary, it is better to follow the path of simplifying migrations, rather than reducing their number.
    • It is better to make migrations as independent from each other as possible.
    • No need to bother with two-way; if some decision turned out to be unsuccessful, it is better to make another migration, which does the opposite operation relative to the previous one, than to roll back.
    • If you add a new field, be sure to make it null first, and only then fill it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question