Basic usage of django2.0 models.py

ORM model Before writing the basic usage of models.py, let's first understand the disadvantages of our own writing of sql: As we write more and ...
ORM introduction
Create ORM model
ORM model

Before writing the basic usage of models.py, let's first understand the disadvantages of our own writing of sql:
As we write more and more projects, if we continue to use native sql statements to write, the following problems will occur:

  • The reuse rate of SQL statements is not high. The more complex SQL statement conditions are, the longer the code is. There will be many similar SQL statements.
  • Many SQL statements are spelled out in the business logic. If there is a database that needs to be changed, it is necessary to modify these logic, which will easily miss the modification of some SQL statements.
  • The sql statements written by ourselves may not be safe enough, which is easy to cause web security problems such as sql injection.

ORM introduction

The full name of ORM is Object Relational Mapping. In Chinese, it is called Object Relational Mapping. Through ORM, we can operate the database by class, instead of writing native SQL statements. By mapping tables to classes, taking rows as instances, and fields as attributes (explained below), ORM will eventually convert the corresponding operations to database native statements when performing object operations.

Create ORM model

prelude

According to the old rules, create a project first:

(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 to open the project. The project directory is 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 Ou test). It's recommended to use naict (because it's simple). After creating a new number, we don't have any tables. Don't worry. Then come on.
Open the settings.py file to modify the database configuration:

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

Written by models.py

Open the models.py file in bookapp, and modify the code 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)

This defines a model. This model inherits from django.db.models.Model. If this model wants to map to the database, it must inherit from this class. This model will be mapped to the database later. The table name is the lowercase form of the model name, which is book. In this table, there are four fields. One is name. This field is the name of the book. It is of varchar type. The maximum length cannot exceed 20 characters and cannot be empty. The second field is the author name type, which is also the varchar type. The length cannot exceed 20. The third is the price of the book, floating point type. Another field we haven't written is the primary key id. in Django, if a model doesn't have a primary key defined, it will automatically generate an int type primary key with the name of id.

  • In Django, some fields are defined to map with the Field types in the database tables. The following will introduce the commonly used Field types (just take this project as an example, simple).
    • AutoField:
      Mapping to the database is of type int, which can have the feature of automatic growth. Generally, this type is not needed. If the primary key is not specified, the model will automatically generate an auto growing primary key called id. You can also use AutoField if you want to specify a primary key with a different name that has automatic growth.
    • CharField:
      At the database level, it is of type varchar. At the Python level, it's a normal string. When using this type, you must specify the maximum length, that is to say, you must pass in the keyword parameter max'length.
    • FloatField:
      Floating point type. Mapping to a database is of type float.
  • If we want to map this Book class to the table of the database, we need to configure settings.py, which is to add this book app to the installed Apus:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'book', ]

Now that the model.py file has been written, if we map this class to the database, django has written us two names, and we can execute the following two commands in turn

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

This command is to generate a database migration script. If no error is reported, you will see the following prompt:

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

And then remember the migrations folder that our app hasn't talked about? Open it and have a look. Here is the folder Directory:

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

There is a 0001 ﹣ initial.py file. As the name implies, initialization. Let's 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)), ], ), ]

When we see this file, we have a sense of sudden realization. django has done some special things for us. We have written the corresponding database of the class we wrote to a new python file, and notice that the IDs of the fields are not defined. We d id not define them in the class at first, but they are automatically defined for us here, and they are of the types of models.AutoField.

  • The migration script has been generated, so it's time to map it to the database. Before mapping, let's take a look at the table in the database. It's empty. In the following line of code, something magical will happen:
    (my_env) F:\ENV\model_test>python manage.py migrate
    If there is no problem, you will be prompted as follows:
    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 a database table:

Yes, it has been successful! Congratulations. Compare with this table, take a closer look at the output of cmd to us after the command of Python management.py migrate, and then think about the installed Apus in settings.py. I believe you will have a new understanding. django is amazing.

Let's sum it up

  • Mapping the ORM model to the database summarizes the following steps:
    • In settings.py, configure DATABASES and make database related configuration.
    • Define the model in models.py in app, which must be inherited from django.db.models.
    • Add this app to the installed app of settings.py.
    • At the command line terminal, enter the path where the project is located, and execute the command python manage.py makemigrations to generate the migration script file.
    • Also on the command line, execute the command python manage.py migrate to map the migration script file to the database.

Here, let's finish first and update MVT as soon as possible! Finally, we call on everyone to wear masks for themselves and 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~~~

hello_coder_kitty Published 2 original articles, won praise 0, visited 280 Private letter follow

1 February 2020, 02:29 | Views: 3540

Add new comment

For adding a comment, please log in
or create account

0 comments