Django: Best Database Design Practices

I am starting a project and I decided to use Django.

My question is about creating a database. I read a tutorial and some books, and they always start to create models and then synchronize the database. I have to say that this is a little strange for me. I always started with the database, defining the schema, and after that I created my database abstractions (models, entities, etc.).

I test some applications with an external connection, and they use this "first model" too.

I see some advantages for the first model approach, such as portability, redeployment, etc.

But I also see some disadvantages: how to create indexes, index type, triggers, views, SP, etc.

So how to start a project in real life?

+6
source share
2 answers

Triggers, views, and stored procedures are not really part of the Django world. It can be used, but it hurts and is not necessary. Django developers believe that the business logic belongs to Python, and not to your database.

As for indexes, you can create them along with your models (with things like db_index and unique_together ), or you can add them later through database migrations using something like South.

+11
source

We basically do not write SQL (for example, create an index, create tables, etc.) for our models and instead rely on Django to generate it for us.

It is perfectly normal to start by developing your application at the model level, as you can rely on Django to create the database SQL code you need.

However, Django provides various functions for replicating these database functions:

  • triggers: Django code or MySQL triggers
  • indexes: can be specified using db_index=True
  • unique constraints: unique = True or unique_togther = (('field1', field2'),) for a complex unique constraint.

The advantage of using Django instead of writing sql is that you abstract from the specific database you are using. In other words, you can be on SQLite one day and switch to PostgresQL or MySQL the next, and the change will be relatively painless.

Example:

When you run this:

 python manage.py syncdb 

Django automatically creates tables, indexes, triggers, etc., it must support the models you created. If you don't like creating django for your database, you can always use:

 python manage.py sqlall 

This will print out the SQL statements that Django will need to have for its models to work properly. There are other sql commands you can use:

see https://docs.djangoproject.com/en/1.3/ref/django-admin/#sql-appname-appname

+7
source

Source: https://habr.com/ru/post/897908/


All Articles