程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[encounter Django] - (II) database configuration

編輯:Python

to encounter Django - Catalog

  Part 1:【 to encounter Django】—— ( One ) Create project

Part 2:【 to encounter Django】—— ( Two ) Database configuration

️ Part 3:【 to encounter Django】—— ( 3、 ... and ) View

️ Part 4:【 to encounter Django】—— ( Four ) Forms and common views

️ Part 5:【 to encounter Django】—— ( 5、 ... and ) Perfect interface ( Customize interfaces and styles )

️ Part 6:【 to encounter Django】—— ( 6、 ... and ) User defined management interface

️ Part 7:【 to encounter Django】—— ( 7、 ... and ) automated testing


List of articles

  •   to encounter Django - Catalog
  •   Preface
  •   One 、 Project profile `settings.py`
    •   1.1 Database configuration
    •   1.2 Time zone and language
    •   1.3 `Django` The default self-contained application profile
  •   Two 、 Creating models
  •   3、 ... and 、 Activate the model
  •   Four 、 First try API
    •   4.1 `Django` Basic use of interactive commands
    •   4.2 Add custom methods to the model
  •   5、 ... and 、`Djaong` Management interface
    •   5.1 Create an administrator account
    •   5.2 Login management interface
    •   5.3 Add voting application to the management page
    •   5.4 Experience convenient management functions
  •   6、 ... and 、【`PyCharm` Use tips 】
    •   6.1 Use `PyCharm` Tools for running `makemigrations & migrate`
    •  6.2 Use `PyCharm` function `django shell`
  •   7、 ... and 、 The simplest beautification Django Admin
    •   7.1 `simpleui` brief introduction
    •   7.2 `simpleui` Use
      •   7.2.1 install
      •   7.2.2 Start using
  •   summary


Preface

This series of articles , stay Django Under the basic template of the official document tutorial , Some improvements and deletions have been made , Added some of my own insights .

I hope that after reading this series of articles , Yes Django Be able to have a clear understanding .

It's a long way to go , I will go up and down !

Django Official documents  https://www.djangoproject.com/

Learning process , Read more official documents , Can solve many problems

This tutorial USES poetry Manage the project environment .
relevant poetry Installation and use of , Please refer to  【Python - A virtual environment 】 The start of the project , Start by isolating the development environment _CoderChaos Technology blog _51CTO Blog

One 、 Project profile settings.py

1.1 Database configuration

mysite/settings.py , It's a that includes Django Project settings Python modular .

Configuration of database , It's the variables DATABASES.

Django By default SQLite As the default database .Python built-in SQLite, So you don't need to install extra things to use .

If you do a real project , Better not to use SQLite.

# Django By default SQLite
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Django Use MySQL To configure 
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysite', # Use MySQL when , Need to be ahead of time MySQL establish mysite database 
'HOST': '127.0.0.1',
'PORT': 3306,
'USER': 'root',
'PASSWORD': '******'
}
}

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

Parameter description :

  • defaultDjango When connecting to the database , Default link default Database under .
  • ENGINE: There are multiple options
    • django.db.backends.sqlite3
    • django.db.backends.postgresql
    • django.db.backends.mysql
    • django.db.backends.oracle
    • Other third-party database backend .  Reference address
  • NAME: Database name . If you use SQLite, The database will be a file on the computer . The default value is BASE_DIR / 'db.sqlite3', The database will be stored in the root directory of the project .
  • The other parameters : If not used SQLite, You must add some additional settings , such as USERPASSWORDHOST wait .  Reference documents

Be careful : If you use SQLite Other databases , You need to make sure that you have created the database before using it . You can use it in your database interactive command line CREATE DATABASE database_name; To complete the creation of the database .

1.2 Time zone and language

Can be in settings.py In file , Modify time zone and language .

# Language 
LANGUAGE_CODE = "zh-hans"
# The time zone 
TIME_ZONE = "Asia/Shanghai"

  • 1.
  • 2.
  • 3.
  • 4.

1.3 Django The default self-contained application profile

settings.py Some notes in the document :INSTALLED_APPS
INSTALLED_APPS The default includes the following Django Built in application of :

  • django.contrib.admin: Administrator site
  • django.contrib.auth: Authentication and authorization system
  • django.contrib.contenttypes: Content type framework
  • django.contrib.sessions: Conversational framework
  • django.contrib.messages: Message frame
  • django.contrib.staticfiles: Framework for managing static files

Some applications opened by default need at least one data table , therefore , Before using them, you need to create some tables in the database . The following commands need to be executed :python manage.py migrate

Two 、 Creating models

Defining models , That is, database structure design and additional metadata .

In this voting application , You need to create two models : problem Question And options Choice.

  • Question The model includes problem description and release time .
  • Choice The model includes the option description and the current number of votes . Each option belongs to a question .
# polls/models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField(" Release date ")
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

Creating models , Inherit django.db.models.Model; Each model has many class variables , Both represent a data table field in the model .

Each field is Field Class .

explain :

  • Django You can create database tables for applications (CREATE TABLE
  • Django Can be created with Question and Choice Objects interact Python database API

3、 ... and 、 Activate the model

Django The application is “ Pluggable ” Of .

add to polls application

# mysite/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
# or 'polls.apps.PollsConfig',
]

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

Now? ,Django The project already contains polls application .

Run the command makemigrations, Perform a migration :python manage.py makemigrations

function makemigrations command ,Django It will detect the modification of the model file , And store the modified part as a migration . Migration is Django A storage of data structure changes .

migrate Is a command that automatically performs database migration and synchronously manages the database structure .

therefore , perform makemigrations after , To modify the synchronization in the database , Need to execute again python manage.py migrate.

Migration is a very powerful feature , It can continuously change the database structure during the development process without deleting tables and recreating tables .
It focuses on smooth database upgrade without data loss .

Changing the model requires the following steps :

  • edit models.py file , Change the model
  • function python manage.py makemigrateions Generate migration files for model changes
  • function python manage.py migrate Application database migration

Four 、 First try API

4.1 Django Basic use of interactive commands

Get into Django Interactive command line :python manage.py shell

>>> from polls.models import Choice, Question
# See the table Question Table data 
>>> Question.objects.all()
<QuerySet []> # There's no data right now 
>>> from django.utils import timezone
# Create a Question Data objects 
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
# Store data objects to the database 
>>> q.save()
# see q Object properties 
>>> q.id
1
>>> q.question_text
"What's' new?"
>>> q.pub_date
datetime.datetime(2022, 3, 20, 11, 29, 15, 780052, tzinfo=datetime.timezone.utc)
# modify q Object properties 
>>> q.question_text = "What's up?"
>>> q.save()
# Look again Question Table data 
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.

about Question Returned display data , You can edit Question Modify the model code , to Question and Chioce increase __str__() Method .

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField(" Release date ")
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

Once again into the Django Interactive command line :python manage.py shell

Question.objects.all()
<QuerySet [<Question: What's up?>]>

  • 1.
  • 2.

4.2 Add custom methods to the model

import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField(" Release date ")
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.

Once again into the Django Interactive command line :python manage.py shell

>>> from polls.models import Question, Choice
# see __str__() Whether it is in effect 
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>
# Django database API:filter
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>
# If there is no data in the database , An exception will be thrown 
>>> Question.objects.get(id=2)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "D:\Codes\media\django\code001\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\Codes\media\django\code001\venv\lib\site-packages\django\db\models\query.py", line 496, in get
raise self.model.DoesNotExist(
polls.models.Question.DoesNotExist: Question matching query does not exist.
# Get data object through primary key 
>>> Question.objects.get(pk=1)
<Question: What's up?>
>>> q = Question.objects.get(pk=1)
# Use models.py Custom methods in 
>>> q.was_published_recently()
True
# see q object , The object corresponding to the foreign key 
>>> q.choice_set.all()
<QuerySet []>
# to q Object to add foreign key elements 
>>> q.choice_set.create(choice_text="Not much", votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text="The sky", votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text="Just hacking again", votes=0)
# see c Elements (Choice object )
>>> c
<Choice: Just hacking again>
# see c Attribute of element 
>>> c.question
<Question: What's up?>
# see q object , The object corresponding to the foreign key 
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()
3
>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> c = q.choice_set.filter(choice_text__startswith="Just hacking")
# Delete c object 
>>> c.delete()
(1, {'polls.Choice': 1})
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>]>

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.

5、 ... and 、Djaong Management interface

The management interface is not for visitors to the website , But for managers .

5.1 Create an administrator account

Run the following command on the command line :python manage.py createsuperuser
You will be prompted later , enter one user name 、 mailbox 、 password 、 Confirm the password .

> python manage.py createsuperuser
user name (leave blank to use 'administrator'): admin
E-mail address : [email protected].com
Password: ******
Password (again): ******
The password length is too short . The password must contain at least 8 Characters .
This password is so common .
The password contains only numbers .
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

5.2 Login management interface

Start development server :python manage.py runserver
Open the browser : http://127.0.0.1:8000/admin/
Enter your account and password , You can enter the management interface .

5.3 Add voting application to the management page

# polls/admin.py
from django.contrib import admin
from .models import Question
admin.site.register(Question)

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

5.4 Experience convenient management functions

Click the button in the page , You can use the add / delete / modify query function .

6、 ... and 、【PyCharm Use tips 】

6.1 Use PyCharm Tools for running makemigrations & migrate

6.2 Use PyCharm function django shell

stay PyCharm Bottom toolbar , choice Python Console You can enter python manage.py shell.

Prerequisite : Project start Django Support .

Project start Django Support see : 【 to encounter Django】——( One ) Create project _CoderChaos Technology blog _51CTO Blog

Four 、【PyCharm Use tips 】

Compared with from Terminal adopt python manage.py shell Get into Django shell, There will be a certain prompt when entering .

7、 ... and 、 The simplest beautification Django Admin

7.1 simpleui brief introduction

Django Admin The default interface design language has some shortcomings , For example, the color is single , The use of a large number of lines , Segmentation is obvious . Categorizing these deficiencies is the monotonous interface 、 The similarity is obvious 、 Lack of surprises .

simpleui: Based on a vue+element-ui Of django admin The theme of modernization .

GitHub Address : https://github.com/newpanjing/simpleui

7.2 simpleui Use

7.2.1 install

poetry add -D django-simpleui

  • 1.

7.2.2 Start using

After installation , In my own project settings.py In file INSTALLED_APPS Of first line Join in simpleui.

# settings.py
INSTALLED_APPS = [
'simpleui',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls'
]

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

If the previous service is still running , Refresh the page .


summary

This article briefly introduces Django Connection and use with database , Use of the default background management interface .

And the use of PyCharm Quick operation makemigrations & migrate Command and django shell, Use django-simpleui Beautify the default background management interface .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved