About Django's core first, db first

db first


Generate class django based on database table :
python manage.py inspectdb

code first

Create database tables based on classes;
django:
python manage.py makemigrations
python manage.py migrate

configuration database

setting.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'sqldb01',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

About db first (reverse generation)

Create a table in the database first

CREATE TABLE users(
         name      VARCHAR(32), )
         extra     VARCHAR(16),
)ENGINE=MyISAM DEFAULT CHARSET=utf8;

Then execute the command to generate the model code

python3 manage.py inspectdb

The generated code model.py is as follows

class Users(models.Model):
    name = models.CharField(max_length=32, blank=True, null=True)
    extra = models.CharField(max_length=16, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'users'

The db_table in here maps the table name in the database.

may report an error

Error loading MySQLdb module: No module named 'MySQLdb'.
Did you install mysqlclient or MySQL-python?

Just install it and run it again

pip3 install mysqlclient

code first (forward generation)

Under the app model.py, write the model.py code

Execute the command to generate the table

python3 manage.py makemigrations
python3 manage.py migrate

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325253104&siteId=291194637