Django study notes

Keywords: Python Django

URL and view functions

URL(Uniform Resource Locator)

form: protocol://hostname[:port]/path[?query][#fragment]
Writing specification:
- absolute address: http://127.0.0.1:8000/test_html_param/Paul
- relative address:
1. '/ page/1' – the result is: http://127.0.0.1:8000/ +/ page/1, add after port
2. 'page/1' - the result is: http://127.0.0.1:8000/test_html_param/ + page/1, add after the last '/'

test_url.html
<a href="http://127.0.0.1:8000/url_ Result "> absolute address</a>
<a href="/url_result">belt/Relative address of</a>
<a href="url_result">No/Relative address</a>
<br>
<a href="{%url 'tr' %}">URL Reverse parsing</a>

test_url_result.html
<p>Test result!</p>

urls.py
path('test/url', test_url),
# path('url_result', test_url_result),
# repath is required for django redirection
# re_path() is only given an alias, which is used in html
re_path('url_result',test_url_result, name='tr'),

views.py
def test_url(request):
    from django.shortcuts import render
    return render(request, "test_url.html")

def test_url_result(request):
    from django.shortcuts import render
    return render(request, 'test_url_result.html')

URL reverse resolution refers to dynamically finding or calculating the corresponding route using re_path definition name in the view or template,
re_path(route, views, name = "alias")

{% url 'alias' %}
{% url 'alias' 'Parameter value 1' 'Parameter value 2' %}
<a href="{%url 'tr' %}">URL Reverse parsing</a>

Processing URL requests

  1. Django finds the main route file from the configuration file according to ROOT_URLCONF; by default, it is urls.py
  2. Django loads the urlpatterns variable in the main route file [an array containing many routes]
  3. Match the path [from diango, URLs import path, report] in urlpatterns to the first appropriate route interrupt
// path('url ', view function)
// re_path('url ', view function, alias)
path('admin/', admin.site.urls)  
re_path('url_result',test_url_result, name='tr')
  1. Matching succeeded - call the corresponding view function to process the request and return the response
  2. Matching failed - 404 response returned

View function

The view function is used to receive a browser request (HttpRequest object) and return a response through the HttpResponse object.

// Syntax:
def home_view(request,[Other parameters]):
    html = "<h1>This is my home!</h1>"
    return HttpResponse object

path converter

Converter types: str (matches non empty strings other than '/'), int (matches 0 or any positive integer, returns an int), slug, path (matches non empty strings including '/').

// Syntax < converter type: custom name >
// Path ('page / < int: Page > ', page_n) passes parameters according to keywords
def page_view(request, pg):
    # html = "<h1>This is number "+str(pg) + " site!</h1>"
    html = "<h1>This is number %s site!</h1>" % (pg)
    return HttpResponse(html)
    
path('page/<int:pg>',page_view),


// Small calculator
def page_cal(request, num1, cal, num2):
    if cal == "add":
        sum = int(num1) + int(num2)
    elif cal == "mul":
        sum = int(num1) * int(num2)
    elif cal == "sub":
        sum = int(num1) - int(num2)
    html = "<h1>The result is  %s !</h1>" % (sum)
    return HttpResponse(html)
    
path('<int:num1>/<str:cal>/<int:num2>',page_cal)

request

The request methods include GET, POST, and HEAD methods (as well as five other rarely used requests: OPTIONS, PUT, DELETE, TRACE, and CONNECT)

In Django, the request is the first parameter request in the view function, that is, the HttpRequest object, which describes all the relevant information of the request through the attribute, eg:

# request.path_info is the path to the request
# request.method is the method of request    
#  request.GET is the object of QueryDict query dictionary, which contains all data of get request method
    	as http://127.0.0.1:8000 / test_request? A = 1 & & B = 2 get {a ': ['1'],'b':['2']}, and the elements are arrays
#  request.POST is the object of QueryDict query dictionary, which contains all data of post request mode
#  request.FILES is similar to a dictionary object and contains all uploaded file information
#  The GET request is just a request to read a page from the server
#  A POST request is a request used when a user needs to submit a form
# COOKIES: a Python dictionary that contains all cookie s. Keys and values are strings
# Session: a dictionary like object that represents the current session
# Body: string, the content of the request body (POST or PUT)
# scheme: request protocol ('http '/'https')
# request.get_full_path(): the full path of the request
# request.META: metadata in the request (message header)
    request.META['REMOTE_ADDR']: client IP address

def test_request(request):
    print("Path info is ", request.path_info)  
    print("Method is ", request.method)  
    print("Querystring is ", request.GET)
    print("Request body is ", request.body)
    return HttpResponse("Test request result!")
path("test_request",test_request)

Whether it is GET or POST, the view function uniformly accepts the request and uses request.method to judge

GET request

GET requests the specified page information and returns the entity body.

Can produce GET Requested scenario:	
	- Enter in the browser address bar URL,After entering
	- <a href="address?parameter=value&parameter=value"
	- form In the form method by get
    if request.method == 'GET':
        print(request.GET)
        print(request.GET['a'])
        print(request.GET.get('c', 'no c'))
        print(request.GET.getlist('c'))
        return HttpResponse(request.method)        

http://127.0.0.1:8000/test_get_post?c=263&a=1000&c=24294 Output results of

POST request

Submit a data processing request to the specified resource. The data is contained in the request body. The POST request may lead to the establishment of new resources and / or the modification of existing resources

POST_FORM = '''
<form method='post' action='test_get_post'>
    user name:<input type='text' name='usname'>
    <input type='submit' value='Submit'>
</form>
'''
def test_get_post(request):
    if request.method == 'GET':
        return HttpResponse(POST_FORM)
    elif request.method == 'POST':
        print("usname is ", request.POST['usname'])
        return HttpResponse("Post is ok!")

http://127.0.0.1:8000/test_get_post Operation results of:
First, the GET request obtains the blank form, and then the POST request submits the form

response

Response status code: - 200 request succeeded
-301 permanent redirection, resources are permanently transferred to other URL s
-302 temporary redirection
-404 the requested resource does not exist
-500 internal server error

Constructor format: HttpResponse(content = response body, content_type = response body data type, status = status code)
Common Content_Type types:

Subclass of HttpResponse: from django.http import HttpResponse, HttpResponseRedirect

Django's design pattern

Traditional MVC (model view controller)
#Reduce coupling between modules
#Model: mainly used to encapsulate the database layer
#View: used to display results to users
#Controller: used to process requests, obtain data, and return results

Django's MTV mode
#Reduce coupling between modules
#Model: responsible for interacting with the database
#Template: responsible for rendering content to the browser (HTML, CSS)
#View: core, which is responsible for receiving requests, obtaining data and returning results
#The primary route is equivalent to the Controller

Template layer

Template configuration
  • Create template folder < project name > / templates
  • Configure the TEMPLATES configuration item in settings.py
    1. BACKEND: Specifies the template engine
    2. DIRS: search directory for templates
    3. APP_DIRS: do you want to search for template files in the templates folder in the application
    4. OPTIONS: OPTIONS for templates
  • Part of configuration item to be modified
    Set DIRS: 'DIRS': [os.path.join(BASE_DIR,' templates')]
Loading method of template

Scheme 1: obtain the template through the loader and respond through HttpResponse

Template:
from django,template import loader
t = loader.get_template("Template file name")
html = t.render(Dictionary data)
return HttpResponsse(html)

Example:
# render method of loader object
from django.template import loader
t = loader.get_template('test_html.html')
html = t.render()
return HttpResponsse(html)

Scheme 2: directly load the response template using render()

Example:
from django.shortcuts import render
    dic = {
        'username': 'paul',
        'age': 21
    }
    # return render(request, 'template file name', dictionary)
    return render(request, 'test_html.html', dic)
    In the view function, use directly locals()Get the variable Dictionary of the view function directly
    return render(request, 'test_html.html',locals())
    In the template, by using{{Variable name}}Syntax to call variables in the view function
Template variables

Data types that can be passed to the template: str (string), int (integer), list (array), tuple (tuple), dict (Dictionary), func (method), obj (object instantiated by class)

<h3>int yes {{int|add:'2'}} </h3> <!-- add:'n' filter-->
    <h3>str yes {{str|upper}} </h3> <!-- upper filter-->
    <h3>lst yes {{lst}} </h3>
    <h3>lst yes {{lst.0}} </h3>
    <h3>dict yes {{dict}} </h3>
    <h3>dict['a'] yes {{dict.a}} </h3>
    <h3>function yes {{func}} </h3>
    <h3>class_obj yes {{class_obj.say}} </h3>
    <h3>Script yes {{script|safe}} </h3><!-- safe filter, Do not string html Translation, Django String translation is enabled by default-->


from django.shortcuts import render
    dic = {}
    dic['int'] = 88
    dic['str'] = 'username'
    dic['lst'] = ['Tom', 'Jerry', 'Lily']
    dic['dict'] = {'a': 9, 'b':7}
    dic['func'] = say_hi
    dic['class_obj'] = Dog()
    dic['script'] = '<script>alter(1111)</script>'
    return render(request, 'test_html_param.html', dic)
def say_hi():
    return "hello"
class Dog:
    def say(self):
        return "nihao!"

Label for template
if tag
def test_if_for(request):
    from django.shortcuts import render
    dic = {}
    dic['x'] = 10
    return render(request, 'test_if_for.html', dic)

In template file
{% if x > 10 %}
the weather is nice today
{% else %}
The weather is very good today.
{% endif %}
<form action="/if_cal" method="post">
    <input type="text" name="x" value={{x}}>
    <option value="add" {% if op == 'add' %} selected {% endif %}> + plus</option>
    <option value="sub" {% if op == 'sub' %} selected {% endif %}> - reduce</option>
    <option value="mul" {% if op == 'mul' %} selected {% endif %}> * ride</option>
    <option value="div" {% if op == 'div' %} selected {% endif %}> / except</option>
    <input type="text" name="y" value={{y}}>  = <span>{{result}}</span>
    <div>
        <input type="submit" value="Start calculation">
    </div>
</form>

def if_cal(request):
    from django.shortcuts import render
    if request.method == 'GET':
        return render(request, 'if_cal.html')
    else:
        x = int(request.POST['x'])
        y = int(request.POST['y'])
        op = request.POST['op']
        if op == 'add':
            result = x + y
        elif op == 'sub':
            result = x - y
        elif op == 'mul':
            result = x * y
        else:
            result = x / y
        # locals() encapsulates variables into a dictionary
        # dic = {'x': x, 'y': y, 'op': op, 'result': result}
        return render(request, 'if_cal.html', locals())
for tag
Syntax:
{% for variable in Iteratable object %}
	Circular statement
{% empty %}
	Statement to fill in when the iteratable object has no data
{% endfor %}


def test_if_for(request):
    from django.shortcuts import render
    dic = {}
    dic['lst'] = ['Tom','Jack','Jerry']
    return render(request, 'test_if_for.html', dic)
    
{% for name in lst%}
    {% if forloop.first %} ########### {%endif%}
    <p>{{forloop.counter}}   {{name}}</p>
    {% if forloop.last %} ********** {%endif%}
{% empty %}
    Now Empty!
{% endfor %}

Built in variable - forloop

Template filter

Definition: process the value of a variable when it is output
Function: you can change the output and display of variables by using filters
Syntax: {{variable | filter 1: 'parameter value 1' | filter 2: 'parameter value' 2 '}}

<h3>int yes {{int|add:'2'}} </h3> <!-- add:'n' filter-->
    <h3>str yes {{str|upper}} </h3> <!-- upper filter-->
    <h3>lst yes {{lst}} </h3>
    <h3>lst yes {{lst.0}} </h3>
    <h3>dict yes {{dict}} </h3>
    <h3>dict['a'] yes {{dict.a}} </h3>
    <h3>function yes {{func}} </h3>
    <h3>class_obj yes {{class_obj.say}} </h3>
    <h3>Script yes {{script|safe}} </h3><!-- safe filter, Do not string html Translation, Django String translation is enabled by default-->


from django.shortcuts import render
    dic = {}
    dic['int'] = 88
    dic['str'] = 'username'
    dic['lst'] = ['Tom', 'Jerry', 'Lily']
    dic['dict'] = {'a': 9, 'b':7}
    dic['func'] = say_hi
    dic['class_obj'] = Dog()
    dic['script'] = '<script>alter(1111)</script>'
    return render(request, 'test_html_param.html', dic)
def say_hi():
    return "hello"
class Dog:
    def say(self):
        return "nihao!"

Inheritance of templates

Template inheritance can reuse the contents of the parent template. The child template directly inherits all the contents of the parent template and can overwrite the corresponding blocks in the parent template.
Syntax:
-Parent template:
1. Define the block label in the parent template
2. Identify which can be modified in the sub template
3. block tag: defined in the parent template and can be overwritten in the child template
-Sub template:
1. Inherit the template extensions tag (written in the first line of the sub template file)
2. The child template overrides the content block in the parent template

Parent template:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% block mytitle %}
    <title>homepage</title>
    {% endblock %}
</head>
<body>
<a href="/music">music</a>
<a href="/sport">Sports</a>
<br>
{% block info %}
This is home.
{% endblock %}
</body>
</html>

Sub template 1:
{% extends 'home.html' %}
{% block mytitle %}
<title>music</title>
{% endblock %}
{% block info %}
This is music.
{% endblock %}

Sub template 2:
{% extends 'home.html' %}
{% block mytitle %}
<title>Sports</title>
{% endblock %}
{% block info %}
This is sport.
{% endblock %}

The child template cannot inherit the variables in the parent template because the variables are in the view function of the parent template. The child template can only call the variables in its own view function

Static file

Static file configuration - settings.py

  1. Access path of configuration static file [exists by default] STATIC_URL = ‘static’
  2. Configure the storage path of static files staticfiles_ Dirs (tuple, which saves the storage location of static files on the server) static files_ DIRS= (os.path.join(BASE_DIR,"static"), )
Method 1
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)

urls.py
from django.contrib import admin
from django.urls import path
from .views import *

urlpatterns = (
    path('admin/', admin.site.urls),
    path('test_static', test_static),
)

views.py
from django.shortcuts import render
def test_static(request):
    return render(request, 'test_static.html')
test_static.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <img src="http://127.0.0.1:8000/static/image/2.jpg" width="200px" height="200px">
    <img src="/static/image/2.jpg" width="100px" height="100px">
</body>
</html>
Method 2

Access static files in the template through the {% static%} tag
More dynamic than relative and absolute paths

  1. Load static- {% load static%}
  2. Use static resource - {% static 'static resource path'%}
    eg: <img src = "{% static 'image/2.jpg'%}"
<img src="{% static 'image/2.jpg' %}" width="150" height="150">

Application of Django

Application in Django project is an independent business module, including its own routing, view, template and model, which is equivalent to a small MTV framework
Create app:

  1. Use the subcommand startapp in manage.py to create an application folder
    python manage.py startapp music
  2. Installed in settings.py_ Configure and install this app in the apps list (array)
    INSTALL_APPS= ['user', 'music',]

Distributed routing

In Django, the main route configuration file (urls.py) can not handle user specific routes. The main route configuration file can distribute requests (distributed request processing). Specific requests can be processed by their respective applications

Configure distributed routing
  1. The from django.urls import path (include) is called in the main routing (include django.urls).
    • Syntax: include('app name. url module name ')
    • Function: it is used to transfer the current route to the urlpatterns of the routing configuration file of each application for distributed processing
  2. urls.py is created under the application, and its structure is the same as that of the main route
Main route
from django.contrib import admin
from django.urls import path,include
from .views import *

urlpatterns = (
    path('admin/', admin.site.urls),
    path('test_static', test_static),
    path('music/',include('music.urls'))
)

music app Lower urls.py
from django.contrib import admin
from django.urls import path
from .views import *

urlpatterns = [
    path('admin/',admin.site.urls),
    path('index',index_view)
]
Template under application
  1. Manually add the templates folder under apply
  2. Enable the TEMPLATE function in settings.py, 'app' in TEMPLATE configuration item_ The value of dirs' is set to True
    When index.html exists in both applied templates and outer templates, django's rules for finding templates are as follows:
    ① Find the templates in the outer templates directory first
    ② According to install_ The application order under apps configuration is found one by one

If there is a file with the same name between the templates folders of two applications, the conflict can be avoided by adding a folder with the same name as the application in the templates directory and placing the template under the folder with the same name as the application

Before modifying, enter http://127.0.0.1:8000/news/index It will jump to index.html under music

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'music',
    'news',
]
from django.shortcuts import render


# Create your views here.
def index_view(request):
    return render(request, 'index.html')

After modification, enter http://127.0.0.1:8000/news/index It will jump to index.html under news
The view function in views.py also needs to be modified

from django.shortcuts import render
def index_view(request):
    return render(request, 'news/index.html')

Model layer (responsible for communicating with the database)

Configure DATABASE, init.py

import pymysql
pymysql.install_as_MySQLdb()

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'book', # Specify the name of the database to connect to
        'USER': 'root', # Specify the user name to log in to the database
        'PASSWORD': '123456', # Database password
        'HOST': '127.0.0.1', # IP and port to connect to specific database
        'PORT': '3306',
    }
}

Model is a Python class and a subclass derived from django.db.model.model
A model class represents a data table in the database
The properties of each class in the model class represent a field in the database
Model is the interface of data interaction and the method and mode of representing and operating database

ORM framework (object relational mapping)

Avoid operating the database through SQL statements
effect:
1. Establish the corresponding relationship between model classes and tables, allowing us to operate the database in an object-oriented way
2. Generate tables in the database according to the designed model class
3. You can switch between databases through simple configuration
4. Realize the decoupling of data model and database, and shield the differences in different database operations

In models.py

from django.db import models

# Create your models here.
class Book(models.Model):
    name = models.CharField("title", max_length=20, default='')
    price = models.DecimalField("Price", max_digits=5, decimal_places=2, default=0.0)

Database migration
python manage.py makemigrations generates migration files
python manage.py migrate executes the migration program to realize migration (data synchronization)

ORM field type

BooleanField()
varchar corresponding to CharField() must specify max_length parameter value
DateField() indicates the date:
- auto_now: this field is automatically set to the current time each time the object is saved (value: True/False)
- auto_now_add: automatically set to the current time when the object is created for the first time (value: True/False)
-default: set the current time (value: time in string format, such as' June 1, 2019 ')
-Only one of the three parameters can be selected
DateTimeField(): represents the date and time
FloatField(): double
DecimalField: decimal
- max_digits: the total number of digits, including the digits after the decimal point. The value must be greater than or equal to decimal_places
- decimal_places: the number of digits after the decimal point
EmailField(): the database type is varchar and the mailbox is stored
IntegerField(): the database type is int

Field options - defines additional information for the created column

primary_key: (value: True/False, default: False)
Blank: (value: True/False) when set to True, the field can be blank; otherwise, the field must be filled in
null: (value: True/False) the default value is False. If it is False, it is recommended to add the default option to set the default value. If it is True, the field can be empty
Default: set the default value of the column. If the field option is null=False, it is recommended to add this item
db_index: (value: True/False) True indicates to add an index to the column
Unique: (value: True/False) True indicates that the value of this field in the database must be unique (it cannot appear repeatedly)
db_column: Specifies the name of the column. If not specified, the attribute name is used as the column name
verbose_name: set the display name of this field on the admin interface

Model class - Meta class

Use the internal Meta class to assign attributes to the model, such as changing the table name,
Before modification:
After modification:

class Book(models.Model):
    name = models.CharField("title", max_length=20, default='')
    price = models.DecimalField("Price", max_digits=5, decimal_places=2, default=0.0)
    info = models.CharField("Book information", max_length= 100,default='')
    class Meta:
        db_table = 'book'
        
class Author(models.Model):
    name = models.CharField("full name",max_length=11)
    age = models.IntegerField("Age")
    email = models.EmailField("mailbox")
    class Meta:
        db_table = 'author'
ORM create data
  1. Mymodel.objects.create (attribute 1 = value 1, attribute 2 = value 2)
    Success: returns the created entity object
    Failed: exception thrown
  2. Create the MyModel instance object and call save() to save it
    Obj = mymodel (attribute = value, attribute = value,)
    obj. Attribute = value
    obj.save()
    Django Shell can be used to operate instead of writing the code of view. The startup mode is python manage.py shell
    If the code changes, you need to restart the shell
    Using these two methods requires the introduction of the model class, from book.models import Book
ORM query data


MyModel.objects.all(): the return value is the QuerySet container object, which stores MyModel instances, which is equivalent to an array of mymodels
You can customize the output format in the MyModel class

 def __str__(self):
        return '%s_%s_%s_%s'%(self.title,self.pub,self.price,self.market_price)
python manage.py shell
>>> from book.models import *
>>> books = Book.objects.all()
>>> books
<QuerySet [<Book: Python_tsinghua university press _20.00_25.00>, <Book: C++_Peking University Press_25.00_40
.00>, <Book: Django_tsinghua university press _70.00_75.00>, <Book: JQuery_Machinery Industry Press_90.00_85.0
0>, <Book: Linux_Machinery Industry Press_80.00_65.00>, <Book: HTML5_tsinghua university press _90.00_105.00>]
>

MyModel.objects.values('column 1 ',' column 2 '): similar to all(), but only look up the required two columns and return a dictionary

>>> books = Book.objects.values('title','pub')
>>> books
<QuerySet [{'title': 'Python', 'pub': 'tsinghua university press '}, {'title': 'C++', 'pub': 'Beijing University
 Science Press'}, {'title': 'Django', 'pub': 'tsinghua university press '}, {'title': 'JQuery', 'pub': 'machine
 Machinery Industry Press'}, {'title': 'Linux', 'pub': 'Machinery Industry Press'}, {'title': 'HTML5', 'pub': '
tsinghua university press '}]>
>>> for book in books:
...     print(book['title'])
...
Python
C++
Django
JQuery
Linux
HTML5

MyModel.objects.values_list(): similar to values, but the return value is a tuple

>>> books = Book.objects.values_list('title','pub')
>>> books
<QuerySet [('Python', 'tsinghua university press '), ('C++', 'Peking University Press'), ('Django', 'Tsinghua University
 press'), ('JQuery', 'Machinery Industry Press'), ('Linux', 'Machinery Industry Press'), ('HTML5', 'Tsinghua University
 press')]>
>>> for book in books:
...     print(book[0])
...
Python
C++
Django
JQuery
Linux
HTML5

MyModel.objects.order_by('column 1 ',' column 2 '):
The default is forward sort. If - is added, it is reverse sort
The return value is QuerySet

>>> books = Book.objects.order_by('price')
>>> books
<QuerySet [<Book: Python_tsinghua university press _20.00_25.00>, <Book: C++_Peking University Press_25.00_40
.00>, <Book: Django_tsinghua university press _70.00_75.00>, <Book: Linux_Machinery Industry Press_80.00_65.00
>, <Book: JQuery_Machinery Industry Press_90.00_85.00>, <Book: HTML5_tsinghua university press _90.00_105.00>]
>
>>> books = Book.objects.order_by('-price')
>>> books
<QuerySet [<Book: JQuery_Machinery Industry Press_90.00_85.00>, <Book: HTML5_tsinghua university press _90.00_
105.00>, <Book: Linux_Machinery Industry Press_80.00_65.00>, <Book: Django_tsinghua university press _70.00_75
.00>, <Book: C++_Peking University Press_25.00_40.00>, <Book: Python_tsinghua university press _20.00_25.00>]
>

After QuerySet, you can continue to use the following methods:

>>> books = Book.objects.order_by('-price').values('title')
>>> books
<QuerySet [{'title': 'JQuery'}, {'title': 'HTML5'}, {'title': 'Linux'}, {'title': 'Djang
o'}, {'title': 'C++'}, {'title': 'Python'}]>
>>> print(books.query) // Get SQL statement
SELECT `book`.`title` FROM `book` ORDER BY `book`.`price` DESC

Mymodel.objects.filter (attribute 1 = value 1, attribute 2 = value 2)
Conditional query, return value QuerySet container object, which stores MyModel instance internally. When there are multiple attributes, multiple attributes are in "and" relationship

PS D:\Python Project\Django test\Test3> python manage.py shell
Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on
 win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from book.models import *
>>> books = Book.objects.filter(pub='tsinghua university press ')
>>> for book in books:
...     print(book.title)
...
Python
Django
HTML5

Mymodel.objects.exclude (condition)
Return all data sets that do not contain this condition, and return QuerySet

Mymodel.objects.get (condition)
Returns the only piece of data that meets the conditions. If there are multiple pieces of data that meet the conditions or none of them meet the conditions, an error will be reported

// Peking University Press returned a piece of data
>>> book1 = Book.objects.get(pub='Peking University Press')
>>> book1
<Book: C++_Peking University Press_25.00_40.00>

// Tsinghua University Press returned three pieces of data
>>> book1 = Book.objects.get(pub='tsinghua university press ')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "D:\Python Project\Django test\Test3\venv\lib\site-packages\django\db\models\mana
ger.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "D:\Python Project\Django test\Test3\venv\lib\site-packages\django\db\models\quer
y.py", line 439, in get
    raise self.model.MultipleObjectsReturned(
book.models.Book.MultipleObjectsReturned: get() returned more than one Book -- it return
ed 3!
query predicate

__ exact: equivalent query

>>> Book.objects.filter(id__exact = 1)
<QuerySet [<Book: Python_tsinghua university press _20.00_25.00>]>

__ Contains: contains the specified value

>>> Book.objects.filter(pub__contains = 'university')
<QuerySet [<Book: Python_tsinghua university press _20.00_25.00>, <Book: C++_Peking University Press_25.00_40
.00>, <Book: Django_tsinghua university press _70.00_75.00>, <Book: HTML5_tsinghua university press _90.00_105.0
0>]>

__ Startswitch: start with xxx

>>> Book.objects.filter(pub__startswith='clear')
<QuerySet [<Book: Python_tsinghua university press _20.00_25.00>, <Book: Django_tsinghua university press _70.00
_75.00>, <Book: HTML5_tsinghua university press _90.00_105.00>]>

__ Endswitch: end with xxx

>>> Author.objects.filter(name__endswith='i')
<QuerySet [<Author: 3_Qi_30_qitx@tedu.cn_>]>

__ gt: greater than the specified value

__ gte: greater than or equal to the specified value

__ lt: less than the specified value

__ lte: less than or equal to the specified value

__ in: find whether the data is within the specified range

>>> Book.objects.filter(pub__in=['tsinghua university press ','Peking University Press'])
<QuerySet [<Book: Python_tsinghua university press _20.00_25.00>, <Book: C++_Peking University Press_25.00_40.00>, <Book: Django_tsinghua university press _70.00_75.00>, <Book: HTML5_tsinghua university press _90.00_105.00>]>

__ Range: find whether the data is within the specified range

>>> Book.objects.filter(price__range=(50,100))
<QuerySet [<Book: Django_tsinghua university press _70.00_75.00>, <Book: JQuery_Machinery Industry Press_90.00_85.00>, <Book: Linux_Machinery Industry Press_80.00_65.00>, <Book: HTML5_tsinghua university press _90.00_105.00>]>
>>> Book.objects.filter(price__range=(75,100))
<QuerySet [<Book: JQuery_Machinery Industry Press_90.00_85.00>, <Book: Linux_Machinery Industry Press_80.00_65.00>, <Book: HTML5_tsinghua university press _90.00_105.00>]>
ORM modify data

Modification of single data

  1. Query - get the entity object to be modified through get()
  2. Change - modify data by object attributes
  3. Save - saves data through the object. save()
>>> author = Author.objects.get(id = 1)
>>> author
<Author: 1_Wang_28_wangweichao@tedu.cn_>
>>> author.age = 49
>>> author.save()
>>> Author.objects.all()
<QuerySet [<Author: 1_Wang_49_wangweichao@tedu.cn_>, <Author: 2_Lv_31_lvze@tedu.cn_>, <Author: 3_Qi_30_qitx@tedu.cn_>]>

Batch data modification
Directly call the update (attribute = value) of QuerySet to realize batch modification

>>> authors = Author.objects.all()
>>> authors.update(age = 70)
3
>>> Author.objects.all()
<QuerySet [<Author: 1_Wang_70_wangweichao@tedu.cn_>, <Author: 2_Lv_70_lvze@tedu.cn_>, <A
uthor: 3_Qi_70_qitx@tedu.cn_>]>
ORM delete data

Single data deletion

  1. Find a data object corresponding to the query result
  2. Call the delete() method of the data object to delete
>>> from book.models import *
>>> book = Book.objects.get(id=4)
>>> book
<Book: JQuery_Machinery Industry Press_90.00_85.00>
>>> book.delete
<bound method Model.delete of <Book: JQuery_Machinery Industry Press_90.00_85.00>>
>>> Book.objects.all()
<QuerySet [<Book: Django_tsinghua university press _70.00_75.00>, <Book: JQuery_Machinery Industry Press_90.00
_85.00>, <Book: Linux_Machinery Industry Press_80.00_65.00>, <Book: HTML5_tsinghua university press _90.00_105
.00>, <Book: Python_tsinghua university press _20.00_25.00>]>

Batch delete data
1. Find all QuerySet query set objects that meet the conditions in the query result set
2. Call the delete() method of the query collection object to delete

>>> books = Book.objects.filter(price__gte=85)
>>> books
<QuerySet [<Book: JQuery_Machinery Industry Press_90.00_85.00>, <Book: HTML5_tsinghua university press _90.00_
105.00>]>
>>> Book.objects.all()
<QuerySet [<Book: Django_tsinghua university press _70.00_75.00>, <Book: JQuery_Machinery Industry Press_90.00
_85.00>, <Book: Linux_Machinery Industry Press_80.00_65.00>, <Book: HTML5_tsinghua university press _90.00_105
.00>, <Book: Python_tsinghua university press _20.00_25.00>]>
>>> books.delete()
(2, {'book.Book': 2})
>>> Book.objects.all()
<QuerySet [<Book: Django_tsinghua university press _70.00_75.00>, <Book: Linux_Machinery Industry Press_80.00_
65.00>, <Book: Python_tsinghua university press _20.00_25.00>]>
>>> print(books.query)
SELECT `book`.`id`, `book`.`title`, `book`.`pub`, `book`.`price`, `book`.`market_price`,
 `book`.`info` FROM `book` WHERE `book`.`price` >= 85

Pseudo deletion
Add a Boolean field (is_active) in the table. The default value is True. Delete is the is of the data to be deleted_ Set the active field to False

F object

An F object represents the field information of a record in the database
effect:
It is usually used to operate on the field values in the database without obtaining them
Comparison between attributes belonging to class
And facilitate multiple users to operate the data. eg: if one hundred microblog users like the same microblog, they will conflict if they first obtain the praise value, then increase and re assign the value
Syntax: from django.db.models import F
F('column name ')

The price of all books increased by 10
Book.objects.all().update(market_price = F('market_price') + 10)
Q object

When complex logical or |, logical non ~ and other operations are used to obtain the query result set, the operation can be carried out with the help of Q object
&And operation
|Or operation
~Non operation
The three operations can be combined
&~And non

>>> from django.db.models import Q

>>> Book.objects.all()
<QuerySet [<Book: Django_tsinghua university press _70.00_75.00>, <Book: Linux_Machinery Industry Press_80.00_
65.00>, <Book: Python_tsinghua university press _20.00_25.00>]>

>>> Book.objects.filter(Q(price__lt=20) | Q(pub='tsinghua university press '))
<QuerySet [<Book: Django_tsinghua university press _70.00_75.00>, <Book: Python_tsinghua university press _20.00
_25.00>]>

>>> Book.objects.filter(Q(price__gt=20) &~ Q(pub='tsinghua university press '))
<QuerySet [<Book: Linux_Machinery Industry Press_80.00_65.00>]>

Posted by o3d on Fri, 10 Sep 2021 19:50:47 -0700