Home Ask Login Register

Developers Planet

Your answer is one click away!

Malik A. Rumi February 2016

Edit database outside Django ORM

If one is using Django, what happens with changes made directly to the database (in my case postgres) through either pgadmin or psql?

How are such changes handled by migrations? Do they take precedence over what the ORM thinks the state of affairs is, or does Django override them and impose it's own sense of change history?

Finally, how are any of these issues effected, or avoided, by git, if at all?



Daniel Roseman February 2016

The migrations system does not look at your current schema at all. It builds up its picture from the graph of previous migrations and the current state of models.py. That means that if you make changes to the schema from outside this system, it will be out of sync; if you then make the equivalent change in models.py and create migrations, when you run them you will probably get an error.

For that reason, you should avoid doing this. If it's done already, you could apply the conflicting migration in fake mode, which simply marks it as done without actually running the code against the database. But it's simpler to do everything via migrations in the first place.

git has no impact on this at all, other than to reiterate that migrations are code, and should be added to your git repo.

Aviah Laor February 2016

You can exclude a model completely from the django migrations, and then you are responsible to adjust the schema to the django code (or the django code to the existing schema):

class SomeModel(models.Model):

    class Meta:
        managed = False  
        db_table = "some_table_name"   

    name = models.Fields....

Note that you can't have it both ways, so migrations are preferred when possible. You can always define a custom SQL migration, that will save the need for external changes. However, sometimes you do need to handle the schema elsewhere instead of migrations, and then use managed=False

Post Status

Asked in February 2016
Viewed 3,761 times
Voted 7
Answered 2 times


Leave an answer

Quote of the day: live life