current position:Home>Django Demo: simple database construction

Django Demo: simple database construction

2022-02-02 14:15:05 Ice sky

link to official tutorial To configure

It's going on Django Before creating a new database , First of all, I need to tell you Django What type of database are we going to create , And which tables need to be created (table), So the first step needs to be changed Complete the corresponding configuration . DATABASES

Start by opening mysite/, In the previous article, I briefly introduced , This is one that contains this Django Files for various configuration definitions of the project .

The default database is SQLite, This is a file on a local computer . If you plan to use Django Databases other than those given , The corresponding... Needs to be installed bingding, And then in Modify the corresponding key value pairs of the phase surface :

    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

among :

  • ENGINE: It can be 'django.db.backends.sqlite3', 'django.db.backends.postgresql', 'django.db.backends.mysql', or ''
  • NAME: Database name . If you are using SQLite, Then the name of the database should be this SQLite The full path to the file , Including the file name . The default value is shown in the code , In the current project directory

Be careful , If not used SQLite, The corresponding user name must be specified additionally , Passwords and hosts TIME_ZONE

Next , take Time zone in TIME_ZONE Set to local time zone , The default is new UTC

#  The default value is TIME_ZONE = 'UTC'

This variable contains this Django All installed and activated in the project app, The default content includes :

    'django.contrib.admin',# admin site
    'django.contrib.auth',# an authentication system
    'django.contrib.contenttypes',# a content types framework
    'django.contrib.sessions',# a session framework
    'django.contrib.messages',# a messaging framework
    'django.contrib.staticfiles',# messaging static files

Some of the above applications need to use at least one database table , Therefore, you need to create the corresponding table before use , adopt :

python migrate

This command will view INSTALLED_APPS What to set up , Then according to the database configuration DATABSES Set up the required table according to the configuration of .migrate namely transfer , Namely Django Used to put Python Operations related to model changes such as model definitions in the code are associated with the database , The whole process is completely made up of Python Code to implement , So there is no need for any SQL Statement can realize the basic operation of the database ( Except for some advanced operations ).
Migration has the following advantages :

  • No need to use SQL Language can modify the database
  • From the created model For migration +2 word , No repetition
  • Use Django Migration Can make when the model changes , Each database can be easily synchronized with the model
  • Easy version management

Database establishment

To configure

  • First , We need to tell Django What type of database are we going to use , That is to say, the Medium DATABASES Variables to configure
  • Modify the corresponding time zone
  • python migrate Create the necessary databases

Creating models

Two models are created in the official example :Questions and Choice

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.CHasrField(max_length=200)
	votes = models.IntegerField

among ,Questions Contains two fields :

  • question_text: That is, the content of this problem , The type is CharField, The maximum length value needs to be indicated
  • pub_date: Release time , The type is DateTime

Chocie Contains two fields and a foreign key :

  • question: This choice Corresponding question object
  • choice_text: Option text , The type is CharField Specify a maximum length of 200
  • votes: Voting data , The type is IntegerField, The default value is 0

You can see , Each class inherits django.db.models.Model, It contains several variables , Each variable corresponds to a field in the database field, Each field has its own field type , Such as DateTimeFIeld,CharField,IntegerField. The corresponding field name is Python Variable names in the code , And the column names in the corresponding database .

Besides , For the constructor of each field , There is an optional parameter in the first position , You can set a variable name with good readability , For example, in pub_date Field creation 'published date'. Besides , Field can also set various other parameters .

ForeignKey Used to tell Django every last Choice Object corresponds to which Question object , Used to define relationships .Django Relationship types supported in :

  • many-to-many
  • many-to-one
  • one-to-one

Activate the model

Through the code above ,Django The following operations will be completed :

  • The scenario of creating a database for this application , namely SQL Medium CREATE TABLE... sentence
  • Create a Python Database access API, Used to deal with Question and Choice Object to access

First, we need to include this application in our project , That is to say Medium INSTALLED_APP Add the reference corresponding to the application configuration . For example, in the example poll project , Its configuration class PollsConfig The path of the class is polls.apps.PollsConfig, So you need to Add :

	# new reference
	# default reference

here ,Django This application will be included in this project . And then through :

python makemigrations polls

Create this application model model Corresponding migration migration, At this time, the corresponding output... Will appear in the terminal :

Migrations for 'polls':
	  - Create model Question
	  - Create model Choice

By creating a migration , take models The changes are stored in the migration , It's essentially a file on a hard disk , for example :polls/migrations/ The corresponding database synchronization will be completed according to this migration later .

Besides , You can also use the following command :

python sqlmigrate polls 0001

You can get the corresponding SQL sentence :

-- 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")
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");


The specific output depends on the type of database configured , We can see :

  • Django Automatically put app Name and model The lowercase names of are combined into the names of the corresponding tables by underlining ( You can customize the naming method )
  • Automatically add primary key ( You can also customize it )
  • commonly Django Will be automatically added to the foreign key name '_id', You can also customize
  • Foreign key associations are displayed as FOREIGN KEY Such constraints

Next , perform migrate

python migrate

migrate All migrations completed for will be performed , Create a table corresponding to the model in the database . therefore , Finally we finished model The steps of change are as follows :

  • stay Modify the model in
  • perform python makemigrations Store model changes in the migration
  • adopt python migrate Finally apply the changes stored in the migration to the database

copyright notice
author[Ice sky],Please bring the original link to reprint, thank you.

Random recommended