How to ignore migrations but __init_.py?

Question:

I’ve been thinking about this.

See here: Should I be adding the Django migration files in the .gitignore file?

I agree with Robert L, it says that we shouldn’t commit our migrations.

My questions are:

1) How to ignore all migrations except for the init.py file that is inside the migrations folder?

2) How to remove migrations that were already committed?

I’m looking to avoid any conflicts between developers.

app structure example:

|_roles
  |__pycache__
     |___init__.cpython-37.pyc
     |_admin.cpython-37.pyc
     |_forms.cpython-37.pyc
     |_models.cpython-37.pyc
     |_urls.cpython-37.pyc
     |_views.cpython-37.pyc
  |_migrations
    |__pycache__
     |___init__.cypthon-37.pyc
     |___0001_initial.cpython-37.pyc
     |___0002_auto_20200111_1307.cpython-37.pyc
     |___0003_auto_20200111_1418.cpython-37.pyc
    |__init_.py
    |_0001_initial.py
    |_0002_auto_20200111_1307.py
    |_0003_auto_20200111_1418.py
   |__init_.py
   |_admin.py
   |_apps.py
   etc..

.gitignore: I’m thinking about:

*./migrations/

But this would exclude the whole folder.

Asked By: Omar Gonzales

||

Answers:

You could use .gitignore. Lines prefixed with a bang (!) are not excluded from gitignore.

So your .gitignore file will look something like

_migrations/*
!_migrations/__init__.py

This would ignore everything in _migrations apart from __init__.py.

To remove files already committed, you can use git rm with the --cached flag…

--cached
Use this option to unstage and remove paths only from the index. Working tree files, whether modified or not, will be left alone.

eg

git rm --cached _migrations/0001_initial.cpython-37.pyc

Finally, I’d also disagree with the statement about not committing migrations. In my option committing them is exactly what you want to be doing. It ensures that instances of the database are consistent across environments. Whilst many migrations in Django are generated code, this isn’t always the case. Possible the most common place you’ll find a migration written by hand is when someone has made a data migration.

In short, commit the migration .py files but exclude all .pyc files.

Answered By: Mat
**/migrations/*

!**/migrations/__init__.py

This code is enough to ignore migrations elegantly

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.