Django series official tutorial [2]Models and the admin site

Continuing from the first chapter, this chapter learns to set up the database, create models and introduce the backend that Django automatically generates.

1. Install the database

Now open mysite/, this is Django's python model settings file.

SQLite is used by default. If we are interested in Django, then this database is enough, python comes with SQLite, no need to install.

If we want to start a real project, we need to use a scalable database like PostgreSQL, which avoids replacing the database halfway (which would be cumbersome).

To put it simply, SQLite is suitable for personal use, mysql can meet the needs of most web applications, and PostgreSQL is currently the most advanced and full-featured, relatively complex database.

Here, take PostgreSQL as an example, install it first.

sudo apt-get update
sudo apt-get install postgresql postgresql-client
sudo apt-get install python3-psycopg2
sudo apt-get install libpq-dev
pip3 install psycopg2

Modify postgresql password

sudo -i -u postgres
psql -U postgres

After viewing the current connection status, fill in the configuration in mysite\

       'NAME':'postgres',#database name
       'USER':'postgres',#Login Username
        'HOST':'',#Database IP address

We can also set the time zone by the way, find a place to add the following code, and then run zoneinfo.available_timezones() You can get all the timezones available, simply use Hongkong here.

import zoneinfo

from django.utils import timezone

class TimezoneMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        tzname = request.session.get('django_timezone')
        if tzname:
        return self.get_response(request)

Test the connection, a row of ok is successful.

python migrate

migrate will create the necessary database according to the installed_app in the settings, we can also use \dt to view the newly created database.

2. Create the model

Now we start to define the model, which is the output of the database

There are two models in this voting model: ask and choose.

Inquiries are questions and data presentations.

The selection has two parts, the text description of the selection and the ballot counter.

First edit polls/

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)

CharField and DateTimeField define the data type of this field, CharField must define the length, the default count of votes is 0, ForeignKey defines the one-to-one relationship between questions and choices, and the relationship between databases can be many-to-one, many-to-many and one-to-one one.

3. Activation model

This small snippet of model code provides Django with a lot of information. With it, Django is able to:

Create the database schema (Create TABLE statement) for this application.

Create a Python database access API for accessing both the question and select objects.

But first we need to tell our project that the voting program is installed.

Also Django apps are plug-and-play: you can use an app in multiple projects, and you can distribute apps because they don't have to be tied to a given Django installation.

To add the app to the project, you need to INSTALLED_APPS This application defines the class PollsConfig in polls/, so the entry name is 'polls.apps.PollsConfig'.

Add the following settings to INSTALLED_APPS in mysite/


After including the app, run the command:

python makemigrations polls

You can see the result:

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

Next, let's see what sql can be run:

python sqlmigrate polls 0001
-- Create model Question
CREATE TABLE "polls_question" ("id" bigserial 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" bigserial NOT NULL PRIMARY KEY, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" bigint 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");

The output varies by database, here are the sql commands we can enter based on the model

Rerun now migrate , to update the model table to the database.

python migrate
Applying polls.0001_initial... OK

The python makemigrations command can be used to build migrations

The python migrate command migrates, which is also the way to upgrade.

4. Play with the API

Now, let's use the free API Django provides: the interactive Python shell. To invoke the Python shell, use the following command:

python shell
>>> from polls.models import Choice, Question  # Import the model you just wrote
# There are currently no question s in the system
>>> Question.objects.all()
<QuerySet []>
#Now to create a question
# It is better to use instead of to set the time.
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?",

# To save an object to the database you must use save()

# Now we have the first record.

# The fields in the model can be accessed through the model.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)

# You can use save() to save the property after changing it.
>>> q.question_text = "what do you want?"

# objects.all() can display all values ​​in the database.
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>

Here we find that the final result is not so intuitive, so we re-modify the question class. In polls/ add:

from django.db import models

class Question(models.Model):
    # ...
    def __str__(self):
        return self.question_text

class Choice(models.Model):
    # ...
    def __str__(self):
        return self.choice_text

It is very important to add the __str__() method, which is not only convenient for us to read, but also easy to automatically generate in Django.

>>> from polls.models import Choice, Question

# M ensures __str__() works.
>>> Question.objects.all()
<QuerySet [<Question: What are your thoughts at the moment?>]>

# Django provides a series of API s for manipulating data
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What are your thoughts at the moment?>]>
>>> Question.objects.filter(question_text__startswith='now')
<QuerySet [<Question: What are your thoughts at the moment?>]>

# Get issues posted this year
>>> from django.utils import timezone
>>> current_year =
>>> Question.objects.get(pub_date__year=current_year)
<Question: What are your thoughts at the moment?>

# access a non-existing ID
>>> Question.objects.get(id=2)
Traceback (most recent call last):
DoesNotExist: Question matching query does not exist.

# Accessing the primary key is the most common case.
# The following method is equivalent to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What are your thoughts at the moment?>

# Make sure the custom method succeeds.
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()

#Now we add question options
>>> q = Question.objects.get(pk=1)

# Show current options
>>> q.choice_set.all()
<QuerySet []>

# Create three options
>>> q.choice_set.create(choice_text='love yourself', votes=0)
<Choice: love yourself>
>>> q.choice_set.create(choice_text='love nature', votes=0)
<Choice: love nature>
>>> c = q.choice_set.create(choice_text='love human beings', votes=0)

# Option to automatically connect with questions
>>> c.question
<Question: What are your thoughts at the moment?>

# all options
>>> q.choice_set.all()
<QuerySet [<Choice: love yourself>, <Choice: love nature>, <Choice: love human beings>]>

>>> q.choice_set.count()

#The API automatically tracks relationships as needed.

#Use double underscores to separate relationships.

#This technique can go to any depth you want; there are no limits.

#Find all options for any issue with a release date this year

#(reuse the 'current_year' variable we created above)
<QuerySet [<Choice: love yourself>, <Choice: love nature>, <Choice: love human beings>]>

# Let's delete one of the choices. Use delete() for that.
>>> c = q.choice_set.filter(choice_text__startswith='spouse')
>>> c.delete()

Fourth, introduce the Django background

Create an administrator

python createsuperuser
Username: admin
Email address:
Password: **********
Password (again): *********
Superuser created successfully.

Open developer services

 python runserver

Now you can type in the browser to log in to the background

we can use LANGUAGE_CODE Modify the interface language, Chinese is zh-hans

Groups and users can be added in the background.

5. Join the application in the background

Now we need to add the application we just wrote to the administrator interface, open polls/, and add:

from django.contrib import admin

from .models import Question

Refresh the background to get our app.

We can also try to add choice as well.

The interface can be played at will.

Chapter 3 covers more about views.

Tags: Python Django PostgreSQL Back-end

Posted by makoy on Tue, 03 May 2022 03:05:12 +0300