English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Django Quick Start-Database models

Django Quick Start-Detailed tutorial on database models

The first part of this tutorial series has been completed. Building on the previous tutorial, in this lecture we will establish a database, create the first model, and use a Django quickly automatically generated admin site.

Database configuration

Now, open mysite/settings.py. Django settings module variables are set at the module level just like normal Python modules.

By default, the configuration uses SQLite. If you are a database novice or want to try learning Django, this is the simplest choice. SQLite is included in Python, so nothing needs to be installed to support your database. When you start your first real project, you may need to use more powerful databases such as PostgreSQL, MySQL, etc., and you can configure the database switch.

If you want to use other databases, please install the corresponding database binding and change the following key in the 'default' configuration item in the database to suit your database connection settings:

ENGINE – Enter 'django.db.backends.sqlite3', 'django.db.backends.postgresql', 'django.db.backends.mysql', or 'django.db.backends.oracle' NAME – The name of the database. If using SQLite, the database will create a file on your computer; in this case, the name should be the full absolute path of the file, including the filename. The default value is os.path.join(BASE_DIR, 'db.sqlite')3), which will store the file in your project directory.

If you do not use SQLite as the database and use other settings such as USER, PASSWORD, and HOST, they must be added. For more detailed information, please refer to Database reference documentation.

When you edit mysite/settings.py, the time zone setting TIME_ZONE.

In addition, please note the INSTALLED_APPS setting at the top of the file. It contains the names of all Django applications activated in this Django example. Applications can be used in multiple projects, and you can package them for others to use in their projects.

By default, INSTALLED_APPS includes the following applications that use Django:

django.contrib.admin – Management site, it will be used quickly here django.contrib.auth – Authentication system django.contrib.contenttypes – A framework, content type django.contrib.sessions – A session framework django.contrib.messages – A messaging framework django.contrib.staticfiles – A framework for managing static files

These applications include the default, as a convenient common example.

Some of these applications use at least one database table, so we need to create the tables in the database before we can use them. To do this, run the following command:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
C:\Python27\mysite>python manage.py migrate
 Operations to perform:
   Apply all migrations: admin, contenttypes, auth, sessions
 Running migrations:
   Rendering model states... DONE
   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 sessions.0001_initial... OK
 C:\Python27\mysite>

The 'migrate' command focuses on the 'INSTALLED_APPS' setting and creates migrations based on your 'mysite'/The database settings in the 'settings.py' file and any database table migrations that come with the application database (we will discuss this in future tutorials). You will see each applicable migration message. If interested, run the command line in your database client, such as type \dt (PostgreSQL), SHOW TABLES; (MySQL), .schema (SQLite), or SELECT TABLE_NAME FROM USER_TABLES; (Oracle) to display the tables created by Django.

Create the model

Now, we will define the model - Essentially, the database is designed using other metadata.

In our simple survey application, we will create two models: Question and Choice. Question has a question title and a publish date. Choice has two fields: choice text and votes. Each choice is associated with a question.

These concepts are represented by simple Python classes. Edit polls/models.py file, so  polls/models.py looks like this:


 # Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
import datetime
 from django.utils import timezone
     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)

The code is straightforward. Each model is a subclass of the django.db.models.Model class. Each model has many class variables, each of which is associated with a field in the database table.

Each field is represented by an instance of the Field class – for example, CharField represents a character field, DateTimeField represents a date-time field. This tells Django the data type of each field.

The name of each Field instance (such as question_text or pub_date) is the name of the field, which is a machine-friendly format. When using this value in Python code, the database will use it as the column name.

Fields can also have different optional parameters; in this example, we have set the default value of votes to 0.

Finally, it is important to note the definition of relationships, here using foreign keys. This tells Django that each option is associated with a question. Django supports all common database relationships: one-to-many, many-to-many, and one-to-one.

Activate the model

The model code is small, but it represents a lot of information about Django. With it, Django can:

Create a database for this application (CREATE TABLE statement)

Create a Python database access API to access the Question and Choice objects

But first we need to tell the 'polls' item which applications are installed.

Edit mysite again/Edit the mysite settings.py file and change the INSTALLED_APPS setting to include the string 'polls.apps.PollsConfig'. The result is as shown below:

mysite/The content of the settings.py file is as follows:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
Now Django knows about the 'polls' voting program. Let's run another command:
# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
C:\Python27\mysite>python manage.py makemigrations polls
 Migrations for 'polls':
   0001_initial.py:
     - Create model Choice
     - Create model Question
     - Add field question to choice
 C:\Python27\mysite>

By running makemigrations, you tell Django that you have made some changes to the model (in this case, it is already up to date), and you want to store these changes as a migration.

Migrations are how Django stores your changes to the model (determined by your database schema)- They are just files on the disk. If you like, you can read the new model migration, it is in the file 'polls':/migrations/0001_initial.py. You wouldn't want Django to read them every time, but they are designed to be editable by humans, so you know how Django changes and can manually adjust them.

There is also a command to run migrations, which automatically manages the database schema (tables): - This is what is called a migration, let's see how SQL knows to run the migration. The 'sqlmigrate' command returns the migration name to the SQL display:


 # Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
$ python manage.py sqlmigrate polls 0001

You should see something similar to the following (we have reformatted it for readability):

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
C:\Python27\mysite>python manage.py sqlmigrate polls 0001
 BEGIN;
 --
 -- Create model Choice
 --
 CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "c
 hoice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
 --
 -- Create model Question
 --
 CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
 "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
 --
 -- Add field question to choice
 --
 ALTER TABLE "polls_choice" RENAME TO "polls_choice__old";
 CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "c
 hoice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer
 er NOT NULL REFERENCES "polls_question" ("id"));
 INSERT INTO "polls_choice" ("choice_text", "votes", "id", "question_id") SELECT
 "choice_text", "votes", "id", NULL FROM "polls_choice__old";
 DROP TABLE "polls_choice__old";
 CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");
 COMMIT;
 C:\Python27\mysite>

The migration command will run all migrations that have not yet been applied (Django tracks which ones are applied in a special table named django_migrations in the database) in the database - Basically, it will use the model to synchronize changes in the database schema.

Using the API

Now, let's enter the interactive Python shell and the API provided by Django. To call the Python command line, please use the following command:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
C:\Python27C:\Python
 \mysite>python manage.py shell 2Python7Python10 . 23 2015(default, May9:44:00) [MSC v., 01500 64 bit (AMD64) on wi
 n32
 Type "help", "copyright", "credits" or "license" for more information.
 (InteractiveConsole)
 >>>

Just type "python" instead, because manage.py sets the DJANGO_SETTINGS_MODULE environment variable, which gives Django Python import paths to mysite/settings.py file.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
>>> import django
 >>> django.setup()
# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
>>> from polls.models import Question, Choice # import the model classes we just wrote.
 # No questions are in the system yet.
 >>> Question.objects.all()
 []
 # Create a new Question.
 # Support for time zones is enabled in the default settings file, so
 # Django expects a datetime with tzinfo for pub_date. Use timezone.now().
 # instead of datetime.datetime.now() and it will do the right thing.
 >>> from django.utils import timezone
 >>> q = Question(question_text="What's new?", pub_date=timezone.now())
 # Save the object into the database. You have to call save() explicitly.
 >>> q.save()
 # Now it has an ID. Note that this might say "1instead of "1depending
 # on which database you're using. That's no biggie; it just means your
 # The database backend prefers to return integers as Python long integer
 # objects.
 >>> q.id
 1
 # Access model field values via Python attributes.
 >>> q.question_text
 "What's new?"
 >>> q.pub_date
 datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
 # Change values by changing the attributes, then calling save().
 >>> q.question_text = "What's up?"
 >>> q.save()
 # objects.all() displays all the questions in the database.
 >>> Question.objects.all()
 [<Question: Question object>]

Here we need to wait a while. The '<Question: Question object>' is a useless representation of this object. Let's solve this problem: by editing the Question model (in the polls/Add a '__str__' method to these Question and Choice models in the models.py file):

polls/The content of the models.py file is as follows:
 # Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
import datetime
 from django.utils.encoding import python_2_unicode_compatible
 @python_2_unicode_compatible # only if you need to support Python 2
 from django.utils import timezone
     class Question(models.Model):
     def __str__(self):
         return self.question_text
 @python_2_unicode_compatible # only if you need to support Python 2
 class Choice(models.Model):
     class Question(models.Model):
     def __str__(self):
         return self.choice_text

It is very important to add the '__str__' method, using interactive prompts to handle adding to the model, which is not only convenient for yourself but also because the object representation is used for the entire Django to automatically generate management.

注意,这些都是正常的Python方法。让我们添加一个自定义的方法,这里只是为了演示:polls/Note that these are all normal Python methods. Let's add a custom method here just for demonstration: polls

 # Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
models.py
 import datetime
 from django.db import models
 from django.utils import timezone
     class Question(models.Model):
     # ...
         def was_published_recently(self): - return self.pub_date >= timezone.now()1)

Note that here we add import datetime and from django.utils import timezone, referencing Python's standard datetime module and Django's time zone-related utilities in django.utils.timezone. If you are not familiar with time zone handling in Python, you can read  Time zone support documentation.

Save these changes and run python manage.py shell again to start a new Python interactive shell:

 # Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
>>> from polls.models import Question, Choice
 # Make sure our __str__() addition worked.
 >>> Question.objects.all()
 [<Question: What's up?>]
 # Django provides a rich database lookup API that's entirely driven by
 # keyword arguments.
 >>> Question.objects.filter(id=1)
 [<Question: What's up?>]
 >>> Question.objects.filter(question_text__startswith='What')
 [<Question: What's up?>]
 # Get the question that was published this year.
 >>> from django.utils import timezone
 >>> current_year = timezone.now().year
 >>> Question.objects.get(pub_date__year=current_year)
 <Question: 怎么了?>
 # 请求一个不存在的ID,这将引发异常。
 >>> Question.objects.get(id=2)
 Traceback (most recent call last):
     ...
 DoesNotExist: 没有匹配查询的问题。
 # 通过主键查找是最常见的用例,因此Django提供
 # primary的快捷方式-key exact lookups.
 # 以下与Question.objects.get(id=)相同1).
 >>> Question.objects.get(pk=1)
 <Question: 怎么了?>
 # 确保我们的自定义方法工作。
 >>> q = Question.objects.get(pk=1)
 >>> q.was_published_recently()
 True
 # 给问题添加几个选择。create调用构建一个新的
 # Choice对象,执行INSERT语句,将选择添加到集合中
 # 可用选择数并返回新的Choice对象。Django创建
 # 用于存储外键关系的“另一侧”的集合
 # (例如,一个问题选择)可以通过API访问。
 >>> q = Question.objects.get(pk=1)
 # 显示相关对象集中任何选择 -- 目前还没有。
 >>> q.choice_set.all()
 []
 # 创建三个选项。
 >>> q.choice_set.create(choice_text='不多', votes=0)
 <Choice: 不多>
 >>> q.choice_set.create(choice_text='天空', votes=0)
 <Choice: 天空>
 >>> c = q.choice_set.create(choice_text='再次破解', votes=0)
 # Choice对象可以通过API访问其相关的Question对象。
 >>> c.question
 <Question: 怎么了?>
 # 反之亦然:Question对象可以访问Choice对象。
 >>> q.choice_set.all()
 [<Choice: 不多>, <Choice: 天空>, <Choice: 再次破解>]
 >>> q.choice_set.count()
 3
 # API会自动跟随所需的关系。
 # 使用双下划线来分隔关系。
 # 可以嵌套到任意深度;没有限制。
 # 查找所有pub_date在本年的任何问题的Choices。
 # (重新使用上面创建的'current_year'变量).
 >>> Choice.objects.filter(question__pub_date__year=current_year)
 [<Choice: 不多>, <Choice: 天空>, <Choice: 再次破解>]
 # 删除其中一个选项。使用delete()函数。
 >>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
 >>> c.delete()

Introduction to Django management

Create an admin user

First, we need to create a user who can log in to the management interface. Run the following command:

 # Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08c:\python27\mysite> python manage.py createsuperuser

Enter the username you want (any one), then press Enter.

 # Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
Username: admin

Then, you will be prompted to enter an email address (any one):

 # Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
Email address: [email protected]

The final step is to enter the password. It will ask for the password twice, the second time for confirmation.

 # Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
Password: **********
 Password (again): *********
 Superuser created successfully.

Start the development server

The Django management site is activated by default. Let's start the development server and explore it.

If the server is not running, start it as follows:

 # Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
c:\python27\mysite>python manage.py runserver

Now, open a web browser and enter "/admin/"Local domain"- For example,   http://127.0.0.1:8000/admin/  You should see the admin login interface:  

Since it is enabled by default, the login screen may display in your own language, and since translation is enabled by default, the login screen may display in your own language,

Enter the admin website

Now, try to log in with the superuser account created in the previous step. You should see the Django management home page:  

You should see some editable content: groups and users. They are provided by django.contrib.auth, Django's authentication framework.

Modify the poll management program

application where is the poll? It will not be displayed on the management index page.

There is only one thing to do: we need to tell the admin that the Question object has a management interface. To do this, open the polls/Modify the admin.py file as follows:  

 # Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.contrib import admin
 from models import Question
 admin.site.register(Question)

Explore management features

Now that we have registered Question, Django knows it should be displayed on the main management page:

Click 'Questions'. Now, view the questions on the 'change list' page. This page displays all questions in the database and allows you to select one to change. There is also the question we created earlier:

Click on the 'What's new?' question to edit:

Items to note are listed here:

 

The form is automatically generated from the Question (Question) model.

 

Different field types (DateTimeField, CharField) correspond to the corresponding HTML input components. Each field type knows how it is displayed in Django management.

Each DateTimeField field gets a JavaScript shortcut. The date gets a 'Today' shortcut and pops up a calendar, and multiple 'Now' shortcuts pop up a window listing common input times.

Modify 'Date published' by clicking the 'Today' and 'Now' shortcuts. Then click 'Save and continue editing.' and then click 'History' in the upper right corner. You will see a page listing all changes made to this object through Django management, with the username of the modifier and timestamp:   Code Download:  http://pan.baidu.com/s/1jGR3wDg