django2.0 models.py basic usage

ORM model

Before writing models.py basic usage, let's take a look at the sql shortcomings of their own to write :
As we write the project is growing, if still continue to use native sql statement to write, then there will be less problems :

  • The more SQL statements recycling rate is not high, the more complex SQL statements condition, the longer the code. Many similar SQL statement appears.
  • Many SQL statement is in the business logic out of the fight, if there is need to change the database, it is necessary to modify the logic, it will be very easy to miss some changes to the SQL statement.
  • Write your own sql statement may security is not high, likely to cause sql injection and other web security issues.

ORM Introduction

ORM called the Object Relational Mapping , Chinese is called object-relational mapping, we can go through the class database operations by way of ORM, rather than write native SQL statements. By mapping table into categories, for example the line, as the field attribute (hereinafter, will be explained), the ORM when performing operation of the object corresponding to the operation will eventually be converted to the native database statement.

Creating an ORM model

Prelude

The old rules, first create a project it:

(my_env) F:\ENV>django-admin startproject model_test

Then create an app (name: book)

(my_env) F:\ENV\model_test>python manage.py startapp book

Use pycharm open the project, the project directory as follows:

F:.
│  manage.py
│
├─.idea
│  │  misc.xml
│  │  model_test.iml
│  │  modules.xml
│  │  workspace.xml
│  │
│  └─inspectionProfiles
│          profiles_settings.xml
│
├─book
│  │  admin.py
│  │  apps.py
│  │  models.py
│  │  tests.py
│  │  views.py
│  │  __init__.py
│  │
│  └─migrations
│          __init__.py
│
└─model_test
    │  settings.py
    │  urls.py
    │  wsgi.py
    │  __init__.py
    │
    └─__pycache__
            settings.cpython-36.pyc
            __init__.cpython-36.pyc

Now create a database (name: model_test), recommended Naicat (because of its simplicity), after the new number, and any table we are not, do not worry, be followed.
Open the settings.py file, modify the database configuration:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'model_test',
        'USER': 'root',
        'PASSWORD': '自己的mysql密码',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

models.py write

Models.py bookapp open file, the code is modified as follows

from django.db import models


class Book(models.Model):
    name = models.CharField(max_length=20,null=False)
    author = models.CharField(max_length=20,null=False)
    price = models.FloatField(default=0)

Above it defines a model. This model inherited from django.db.models.Model, if the model you want to map to the database, you must inherit from this class. This model later mapped to the database, table name is lowercase name of the model for the book. In this table, there are four fields, one for the name, this field is saved is the name of the book, varchar type is no longer than 20 characters, and can not be empty. The second field is the type of author's name, is also a varchar type, length can not be more than 20. The third is the price of this book, is a floating-point type. There is also a field we did not write, is the primary key id, in django, if a model does not define a primary key, it will automatically generate an automatic increase of type int primary key, and the name of the primary key called id.

  • In Django, defined to be some Field mapping database table field type. The following describes those common field types (only used in this project, for example, simple).
    • AutoField :
      mapping to the database is int type, you can have characteristics of automatic growth. Generally you do not need to use this type, if you do not specify a primary key, then the model will automatically generate a called id of the automatic growth of the primary key. If you want to specify a different name and with automatic growth of the primary key, use AutoField also possible.
    • CharField :
      at the database level is varchar type. In Python level is normal string. This type must specify a maximum length when in use, that must be passed max_length keyword parameters into account.
    • FloatField :
      floating-point type. The database is mapped to a float.
  • If we want this Book class corresponds to a database table, then we also need to configure settings.py, is this Book App Add to INSTALLED_APPS in:
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'book',
]

Now models.py file has been finished, this class if we map it to the database, django good for us to write two names, in turn execute the following two commands to ok

(my_env) F:\ENV\model_test>python manage.py makemigrations

This command is to generate database migration script, if there is no error, you will see the following prompt:

Migrations for 'book':
  book\migrations\0001_initial.py
    - Create model Book

Then also remember that we have not mentioned the app migrations folder? Open look, here is the folder directory:

F:.
│  0001_initial.py
│  __init__.py
│
└─__pycache__
        __init__.cpython-36.pyc

There is a 0001_initial.py file, by definition, initialization, we look at the source code:

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Book',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=20)),
                ('author', models.CharField(max_length=20)),
                ('price', models.FloatField(default=0)),
            ],
        ),
    ]

We see the basic feeling that there is a file suddenly realized, django has done for us some special things, we will write the corresponding database class wrote a new python file, noting fiels of id no, we did not at first class definition, but here automatically help us define, and is models.AutoField type.

  • Migration scripts have been generated, then now is the time to map database inside. Before the mapping, we look at the database table is empty, the following line of code, amazing things will happen:
    (my_env) F:\ENV\model_test>python manage.py migrate
    
    If not, there will be the following tips:
    Operations to perform:
    Apply all migrations: admin, auth, book, contenttypes, sessions
    Running migrations:
    Applying contenttypes.0001_initial... OK
    Applying auth.0001_initial... OK
    Applying admin.0001_initial... OK
    Applying admin.0002_logentry_remove_auto_add... OK
    Applying contenttypes.0002_remove_content_type_name... OK
    Applying auth.0002_alter_permission_name_max_length... OK
    Applying auth.0003_alter_user_email_max_length... OK
    Applying auth.0004_alter_user_username_opts... OK
    Applying auth.0005_alter_user_last_login_null... OK
    Applying auth.0006_require_contenttypes_0002... OK
    Applying auth.0007_alter_validators_add_error_messages... OK
    Applying auth.0008_alter_user_username_max_length... OK
    Applying auth.0009_alter_user_last_name_max_length... OK
    Applying book.0001_initial... OK
    Applying sessions.0001_initial... OK
    

Now look at the table in a database:
After the migration table
right, has been a success! Congratulations. Shining on the table, after a closer look at Python manage.py the migrate cmd after command output to us, think again settings.py in INSTALLED_APPS , I believe we will have a new understanding, django is amazing.


Summarize it

  • The ORM model is mapped to the database, summed up the following steps:
    • In settings.py, the configured DATABASES, do database-related configuration.
    • Model has been defined in the app in models.py, this model must inherit from django.db.models.
    • Add this app to INSTALLED_APP settings.py in.
    • In the terminal command line, enter the path to the project is located, and then execute the command python manage.py makemigrations to generate the migration script file.
    • Also in the command line, execute the command python manage.py migrate to migrate script files are mapped to the database.

Here, first come to an end, the future will be updated as soon as possible MVT ! The last appeal to everyone to go out wearing masks, for themselves and for the country.

In [1]: from datetime import datetime

In [2]: datetime.now()
Out[2]: datetime.datetime(2020, 2, 1, 15, 2, 41, 743080)

Punch completed ~ ~ ~

Released five original articles · won praise 0 · Views 363

Guess you like

Origin blog.csdn.net/qq_33694648/article/details/104133149