Tuesday, May 3, 2016

Re: Help with defining Models for ManyToMany and OneToMany relationships...

Hi Bruce,

On Mon, May 02, 2016 at 02:31:37PM -0700, Bruce Whealton wrote:
> Michal,
> I had to read your response a few times but I finally got it. I was
> reading
> that all migrations are created in development only and then applied during
> production.
> So, during development you use makemigrations and then when deployed
> you migrate.
>
> Thus, if you add a new feature, you make the migration on the
> development system then push it to producation, where you can
> issue the command python manage.py migrate.

Yes, that sounds correct.

> I just thought of something that is related to migrations. Suppose,
> with my contacts app, I want to change the name field to be
> first_name + last_name. If there is data in the database, how will
> this be handled?


There's a description of almost exactly this kind of migration in the
docs:
https://docs.djangoproject.com/en/1.9/topics/migrations/#data-migrations

To give you a more complete overview of how to do that, first, you
create a migration to add the new columns, after which you should have
both the old columns, and the new ones in the database at the same
time. This is a regular schema migration.

Then, you create a data migration which will read data from the old
columns, do any processing, and save the data in new columns. This is
usually called a data migration, and is achieved using the RunPython
migration operation. Alternatively, if you are comfortable with SQL,
and if you are able to express the data transformation in a few SQL
queries, you can use RunSQL instead.

Finally, you create a third migration – another schema migration, in
which you just remove the old columns.

If you want to be able to apply the data migration in reverse, you'll
also have to define a function (or SQL statements) that will perform
the reverse operation. This is optional, but it might come in handy
sometimes, such as when switching between development branches where
each branch has a different set of migrations.


As a final note, you can use the same technique for example if you
want to add a non-nullable unique field to a database that already
contains data. The docs contain a quick walkthrough for this kind of
operation:
https://docs.djangoproject.com/en/1.9/howto/writing-migrations/#migrations-that-add-unique-fields


Does this help?

Michal

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20160503074848.GS435%40koniiiik.org.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment