Alex S
Alex S

Reputation: 239

Django migrations for docker container

I have been trying to resolve an issue i am having currently, but i have not found any adequate solution neither here or elsewhere, so i was hoping someone here might have an answer. I have gotten to a point where i know what the problem is but not how to resolve it.

Basically i have a website running django/postgres/nginx, it runs smoothly and i can make new models and migrate them, but if i try to add a field to the model:

from django.db import models

class project(models.Model):
    project_name = models.CharField(max_length=50)
    author = models.CharField(max_length=30, blank=True, null=True)
    date_created = models.DateField()
    #Added in second round of migrations 
    #Description = models.CharField(max_length=150,blank=True, null=True)

What i would normally do is initially build and spin up my container

sudo docker-compose -f docker-compose.yml up --build

And within my entrypoint file i run makemigrations and migrate.

The first round it works well, but if i add the Description field to my model, spin down and rebuild the container to allow the new field to be included in my container, the new container is build without the initial migration, and isntead with a new migration. This results in any previous postgres tables not getting the new field added and a server error 500 when i try to request the data as previous tables now do not have the expected columns.

Therefore my question is how would you normally manage models for containerized django apps to ensure you maintain all migrations? Or is there another solution i am not aware of?

It might be a silly question but i am quite new to this and would appreciate any help you could offer.

Upvotes: 2

Views: 1321

Answers (2)

atline
atline

Reputation: 31584

makemigrations should be done in development phase, and add the migrate files (000x prefix files) to source control.

Then, after several times' modify, you should have something like:

0001_first_round_change.py
0002_second_round_change_for_description.py
......

Every time when docker container start, migrate these files, a useful procedure for this operation could be seen in Django Commands: makemigrations or migrate?

And, here is an opensource project example which they use the same method to do migrate, FYI.

Upvotes: 1

elonzh
elonzh

Reputation: 1324

  1. The migrate operation is dangerous and you should never do it automatically.
  2. The recommended default behavior of entrypoint file is running your app server.
  3. If you want to migrate your database, try docker exec for running command in container.

Upvotes: 1

Related Questions