Migrations is so useful for developer specially django, but sometime we have conflicts. Now, I will explain why have conflicts and way to resolve.

Migrations conflict is same with github conflict when many branch change one thing together. Technically, django invest migrations with same prefix number then require developer to merge them.

For example, master branch create model User. After then, branch 1 add field email with migration file: 0002_email.py. At the same time, branch 2 add field avatar with migration file: 0002_avatar.py. Then, we merge 2 branch in master and conflict blow in because of same 0002 in migration file. Fortunately, django support fix conflict completely by this terminal.

python manage.py makemigrations --merge

0003_merge.py, is created inside the migrations folder by django.


Another point make confuse in django migration is comeing to null and blank. null is purely database-related in database part, whereas blank is validation-related in django part.

  • null=False, blank=False: required in all circumstances

  • null=True, blank=True: optional in all circumstances

  • null=True, blank=False: This means database don't require value (Allow Null in DB) but form require value

  • null=False, blank=True: This means database require value (Not Null in DB) but form don't require value



Finally, I talk about add not null field in existing model without default value. The problem is django requires default value for existing records in database.

Image

I usually bear up by these steps:

  • SET null=True, blank=True

  • Migrate your database py manage.py makemigrations and py manage.py migrate

  • Fill data for existing rows by manual migrations.

  • SET null=False, blank=False

  • Migrate again

Steve Nguyen

© Steve CV. All rights reserved.
Design - TemplateFlip