django learning - Database Configuration - create a model

 Database Configuration

In mysite / settings.py, the modules comprising the python django project settings

 

Typically, this configuration file uses SQLite as the default database. If you are not familiar with the database, or just want to try django, this is the easiest choice. python built-in SQLite, so you do not need to use it to install extra stuff. When you start a real project, you might prefer to use a more scalable databases, such as PostgreSQL, a database switch to avoid the middle of the headaches.

 

If you want to use a different database, you need to install the appropriate database bindlings, and then change the settings file DATABASE 'default' projects in some of the key:

E.g:

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

 

  

DATABASE 'default' a number of key projects
ENGINE- database type optional values:
'django.db.backends.sqlite3'
'django.db.backends.postgresql'
'django.db.backends.mysql'
'django.db.backends.oracle'

 

The name of the database NAME-

If you are using SQLite, the database will be a file on your computer, in this case, NAME should be the absolute path to the file, including the file name. The default value os.path.join (BASE_DIR, 'db.sqlite3') will put the database files are stored in the root directory of the project.

 

If you are not using SQLite, you must add some additional settings, such as USER, PASSWORD, HOST, and so on.

 

Such as:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

 

Other than the SQLite database

If you are using a database other than SQLite, please confirm before use have created a database. You can use your database interactive command line "CREATE DATABASE database_name;" command to get this done.

 

Also make sure that the database users with operating mysite / settings.py have "create database" permissions. This makes the tutorial after test database can be created automatically.

 

If you're using SQLite, name you do not need to do anything before use - the database is created automatically when needed.

 

Former editor mysite / settings.py file, first set the TIME_ZONE for your own time zone.

 

In addition, look INSTALLED_APPS settings file header. This contains all the django application enabled in your project. Application can be used in multiple projects, you can also package and publish the application, let others use them.

E.g:

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

 

INSTALLED_APPS

Usually, INSTALLED_APPS including the default application comes with django of the following:

 

django.contrib.admin- site administrator

django.contrib.auth- authentication and authorization system

django.contrib.contenttypes- content type framework

django.contrib.sessions- session framework

django.contrib.messages- message frame

Management framework django.contrib.staticfiles- static files

 

These applications are enabled by default in order to provide convenience to the general project.

Enabled by default for certain applications require at least one data table, so you need to create some tables in the database before using them.

py -3 manage.py migrate database migration command

The migrate command to check INSTALLED_APPS settings, create data tables needed for each application of them, as to what specifically will create, depending on your database migration file mysite / settings.py files and settings for each application. This command is executed for each migration operation will be displayed in the terminal.

 

Can run the show tables; see what tables are created specifically django:

 

 

django some applications enabled by default, but not everyone needs them. If we do not need one or some applications, notes or delete them from the inside before running INSTALLED_APPS migrate.

migrate database migration command will only be declared for the application of the INSTALLED_APPS years.

 

Create a model

Write a database-driven web applications in django in the first step is to define the model - that is, the database structure design and other additional metadata.

 

Model is simple and clear description of real data. It contains the necessary data storage fields and behavior. django follow the DRY Principle (non-repetition-create the wheel). Its goal is that you only need to define the data model, and other assorted code that you do not care, they will be automatically generated from the model.

 

To introduce migration - for example, django the migration code is automatically generated by your model file, which is essentially just a history, django can use it to scroll updating the database, and in this way it can the current model matching.

 

In this simple voting application, you need to create two models: issues and options Question Choice. Question model includes description of the problem and release date. Choice model has two fields, options, and describes the current number of votes. Each option belonging to a problem.

 

These concepts can be described by a simple python class. The following example to edit polls / models.py file:

 

from django.db import models

# Create your models here.

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)

Code is very straightforward, each model is represented as a subclass of the class django.db.models.Model. Each model has a number of class variables, they said model in a database field.

 

Field each field is an instance of the class - for example, a character field is denoted as CharField, date and time is expressed as DateTimeField. This high-speed django data type for each field to be treated.

 

Name (e.g. question_text or pub_date) Field of each class instance variables are field names, it is preferable to use machine-friendly format. You will use them in pythob code, and the database will be it as the column name.

 

You can use the optional Field option to define a human-readable name. This feature in many interior components of django are being used, but also as part of the document. If a field does not provide this name, django will use the machine-friendly name, which is the variable name.

In the above example, we only define the human-friendly name for Question.pub_date. For other fields within the model, their machine-friendly name will be used as a human-friendly name.

 

Field Definitions for certain parameters need class instance. For example CharField need a max_length parameters. Usefulness of this parameter will not be used to define the database structure, is also used to validate the data, we see something in this regard later.

 

Field can receive a plurality of optional parameters; in the example above: the default will be votes is the default value, is set to 0.

 

Note that in the end, we use ForeighKey define a relationship. This high-speed django, each Choice objects are associated to a Question object. django supports all common database relationships: many-to-many and one to one.

 

 

Activation model

The above code is used to create a model of a team to a django lot of information, this information, you can do some things django:

1) Create a database schema for this application (generated CREATE TABLE statement)

2) Create a python can interact with the database API Question and Choice objects

 

But first you have to install the polls applied to our project in

 

Design philosophy:

django applications are "pluggable" in. You can use the same application across multiple projects. In addition, you can also publish their own applications, because they do not bind to the django currently installed.

 

To include this application in our project, we need to add the settings in the configuration class INSTALLED_APPS in. Because the file written in the class PollsConfig polls / app.py in the path point so it is 'polls.apps.PollsConfig'. After the file mysite / settings.py in INSTALLED_APP subkeys point path, 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 include polls applications. Then run the following command:

py -3 manage.py makemigrations polls generate migration

 

You will see this output similar to the following:

 

Makemigrations by running the command, django detects (new in this case, you have achieved) you modify the model file and stored as part of the modification of a migration.

 

Migration is for django model definition (that is, your database structure) is stored in the form of changes - not so iffy, in fact, they are just some of the files on your disk, you can read migrate data model, in polls / migrations / 0001_initial.py in. As shown below:

 

 

 

django has an automated data migration and synchronization management of your database results of command - This command is migrate, we immediately come into contact with it.

But first, let's look at what sql statement will execute the migration command.

sqlmigrate command receives the name of a migration, then returns the corresponding SQL:
py -3 manage.py sqlmigrate polls 0001

You will see something like the following output (the output reorganization became a human-readable format):

D:\django\mysite>py -3 manage.py sqlmigrate polls 0001

BEGIN;

--

-- Create model Question

--

CREATE TABLE `polls_question` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `question_text` varchar(200) NOT NULL, `pub_date` datetime(6) NOT NULL);

--

-- Create model Choice

--

CREATE TABLE `polls_choice` (`id` integer AUTO_INCREMENT 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`);

COMMIT;

 

 

Please note the following:

1) output content and databases related to your use of the output of the above examples use mysql

2) the name of the database table by lowercase application name (polls) and the model name (Question and Choice) connecting from. (If desired, you can customize this behavior.)

3) primary key (IDs) are created automatically. (Of course, you can also customize)

4) default, django will append a key field outside the string "_id". (Likewise, it can be customized.)

5) there is a foreign key relationship FOREIGN KEY generated. You do not care about DEFERRABLE part (for PostgreSQL), it refers to tell PostgreSQL, please re-create a foreign key relationship after all transactions executed.

6) generated SQL statement is customized for your use of the database, so those, and database-related field types such as auto_increment (MySQL), serial (PostgreSQL) and integer primary key autoincrement (SQLite), django will help you automatically. Those things and quotes related - for example, to use single quotes or double quotes - the same will be handled automatically.

7) This sqlmigrate not actually perform the migration command in your database - it just outputs the command to the screen, allowing you to see what think django sql statements need to execute. This is useful when you want to see django in the end going to do, or if you are a database administrator, you need to write a script to batch processing database.

 

py -3 manage.py check inspection items

Py -3 manage.py check can run commands to help you check the items in question, and the database will not carry out any operation in the inspection process

 

Run the migrate command to create a new data model table defined in the database:

 

D:\django\mysite>py -3 manage.py migrate

Operations to perform:

  Apply all migrations: admin, auth, contenttypes, polls, sessions

Running migrations:

  Applying polls.0001_initial... OK

 

The migrate command to select all the migration has not been executed (django by creating a special table django_migrations in a database to track performed which migrate) and applications on the database - that is, you change the model synchronized to the database structure.

 

Migration is a very large feature that allows you to change the data structure in the ongoing development process without the need to re-create and delete tables - it focuses so smooth upgrade the database without losing data. We will learn more in-depth later in this part of the tutorial, now, as long as you remember to change the model requires the following three steps:

 

Step model of change

1) Edit models.py file, change the model.

2) Run python manage.py makemigrations generate migrate files to change the model

3) Run python manage.py migrate to application database migration

 

Database migration is broken down into two commands are generated and applied in order to allow you to submit data on migration code control system and enable it to be used in multiple applications in; this will not only make development easier, but also to other developers and use the production environment convenience.

 

Guess you like

Origin www.cnblogs.com/xiaxiaoxu/p/11665801.html