Convert Django model to database data

Create a model

The first step in writing a database-driven Web application in Django is to define the model-that is, the database structure design and additional metadata.

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

Each model is represented as a subclass of the django.db.models.Model class. Each model has many class variables, and they all represent a database field in the model.

Each field is an instance of the Field class-for example, a character field is represented as CharField, and a date and time field is represented as DateTimeField. This will tell Django the type of data to be processed for each field.

The name of each instance variable of the Field class (such as question_text or pub_date) is also a field name, so it is best to use a machine-friendly format. You will use them in Python code, and the database will use them as column names.

You can use the optional options to define a human-readable name for the Field. This feature is used in many internal parts of Django and is part of the documentation. If this name is not provided for a field, Django will use the machine-friendly name, which is the variable name. In the above example, we only defined a human-friendly name for Question.pub_date. For other fields in the model, their machine-friendly names will also be used as human-friendly names.

Parameters are required to define certain instances of the Field class. For example, CharField requires a max_length parameter. The use of this parameter is not only used to define the database structure, but also used to verify data.

Field can also receive multiple optional parameters; in the above example: we set the default value of votes, which is the default value, to 0.

Note that at the end, we defined a relationship using ForeignKey. This will tell Django that every Choice object is associated with a Question object. Django supports all common database relationships: many-to-one, many-to-many, and one-to-one.

Activation model

The above snippet of code used to create the model gives Django a lot of information. With this information, Django can:

Create a database schema for this application (generate CREATE TABLE statement).
Create a Python database API that can interact with Question and Choice objects.

But first we have to install the polls application into our project.
In order to include this application in our project, we need to add settings in the configuration class INSTALLED_APPS. Because the PollsConfig class is written in the file polls/apps.py, its dotted path is'polls.apps.PollsConfig'. After adding a dotted path to the INSTALLED_APPS subkey in the file projectName/settings.py , it looks like this:

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Now your Django project will contain the polls application. Then run the following command

$ python manage.py makemigrations polls

You will see output similar to the following:

Migrations for 'polls':
  polls/migrations/0001_initial.py
    - Create model Question
    - Create model Choice

By running the makemigrations command, Django will detect your changes to the model file (in this case, you have already obtained a new one), and store the changes as a migration.

Migration is Django's storage form for changes to model definitions (that is, your database structure)-they are actually just some files on your disk. If you want, you can read the migration data of your model, which is stored in polls/migrations/0001_initial.py. Don't worry, you don't need to read the migration files every time, but they are designed to be human-readable. This is to allow you to manually adjust the way Django changes.

Django has a command that automatically performs database migration and manages your database structure synchronously-this command is migrate, and we will touch it shortly-but first, let's see which SQL statements are executed by the migration command. The sqlmigrate command receives a migration name and returns the corresponding SQL:

$ python manage.py sqlmigrate polls 0001

You will see output similar to the following (I reorganized the output into a human-readable format):

BEGIN;
--
-- Create model Question
--
CREATE TABLE "polls_question" (
    "id" serial NOT NULL PRIMARY KEY,
    "question_text" varchar(200) NOT NULL,
    "pub_date" timestamp with time zone NOT NULL
);
--
-- Create model Choice
--
CREATE TABLE "polls_choice" (
    "id" serial NOT NULL PRIMARY KEY,
    "choice_text" varchar(200) NOT NULL,
    "votes" integer NOT NULL,
    "question_id" integer NOT NULL
);
ALTER TABLE "polls_choice"
  ADD CONSTRAINT "polls_choice_question_id_c5b4b260_fk_polls_question_id"
    FOREIGN KEY ("question_id")
    REFERENCES "polls_question" ("id")
    DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");

COMMIT;

The database table name is concatenated by the application name (polls) and the lowercase form of the model name (question and choice). (You can customize this behavior if you want.)
Primary keys (IDs) will be created automatically. (Of course, you can also customize it.)
By default, Django will append the string "_id" after the foreign key field name. (Also, this can be customized.) The
foreign key relationship is generated by FOREIGN KEY. You don't need to care about the DEFERRABLE part, it just tells PostgreSQL to create the foreign key relationship after all transactions are executed.
The generated SQL statements are customized for the database you are using, so the field types related to the database, such as auto_increment (MySQL), serial (PostgreSQL), and integer primary key autoincrement (SQLite), will be processed automatically by Django for you. Things related to quotation marks-for example, whether to use single or double quotation marks-will also be handled automatically.
The sqlmigrate command does not actually perform migration in your database-instead, it just outputs the command to the screen, letting you see which SQL statements Django thinks need to be executed. This is useful when you want to see what Django is going to do, or when you are a database administrator and need to write scripts to process databases in batches.
Now, run the migrate command again to create the data table of the newly defined model in the database:

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Rendering model states... DONE
  Applying polls.0001_initial... OK

This migrate command selects all migrations that have not been executed (Django tracks which migrations have been executed by creating a special table django_migrations in the database) and applies them to the database-that is, to synchronize your changes to the model to the database structure.

Migration is a very powerful feature, it allows you to continuously change the database structure during the development process without the need to re-delete and create tables-it focuses on smoothly upgrading the database without data loss. We will learn more about this part in the following tutorials. For now, you only need to remember that changing the model requires these three steps:

  1. Edit the models.py file to change the model.
  2. Run python manage.py makemigrations to generate migration files for model changes.
  3. Run python manage.py migrate to apply the database migration.

The database migration is divided into two commands, generation and application, so that you can submit the migration data on the code control system and make it available in multiple applications; this will not only make development easier, but also give other developers And the use in the production environment brings convenience.

Guess you like

Origin blog.csdn.net/p715306030/article/details/113198431