Elias Bothell
Elias Bothell

Reputation: 85

How can I add new models and do migrations without restarting the server manually?

For the app I'm building I need to be able to create a new data model in models.py as fast as possible automatically.

I created a way to do this by making a seperate python program that opens models.py, edits it, closes it, and does server migrations automatically but there must be a better way.

edit: my method works on my local server but not on pythonanywhere

Upvotes: 0

Views: 219

Answers (2)

almost a beginner
almost a beginner

Reputation: 1632

In the Django documentation, I found SchemaEditor, which is exactly what you want. Using the SchemaEditor, you can create Models, delete Models, add fields, delete fields etc..

Here's an excerpt:

Django’s migration system is split into two parts; the logic for calculating and storing what operations should be run (django.db.migrations), and the database abstraction layer that turns things like “create a model” or “delete a field” into SQL - which is the job of the SchemaEditor.

Upvotes: 1

stefanw
stefanw

Reputation: 10570

Don't rewrite your models.py file automatically, that is not how it's meant to work. When you need more flexibility in the way you store data, you should do the following:

  • think hard about what kind of data you want to store and make your data model more abstract to fit more cases, if needed.
  • Use JSON fields to store arbitrary JSON data with your model (e.g. for the Postgres database)
  • if it's not a fit, don't use Django's ORM and use a different store (e.g. Redis for key-value or MongoDB for JSON documents)

Upvotes: 0

Related Questions