Python study notes --Day11

Python study notes --Day11

Django next day.

SNAKE

ORM (Object-Relation Mapping) means that object - relational mapping, by using metadata mapping between objects and description databases, object-oriented target program automatically persisted to a relational database. Essentially data is converted from one form to another form. This also implies additional execution overhead; however, if the ORM as a kind of middleware, will have the opportunity to do a lot of optimization, which does not exist in the handwriting of the persistence layer. More important it is to control the conversion and the need to provide metadata management; but again, these costs than to maintain hand-written programs less; and even if compliance with norms ODMG object database still needs class metadata level.

ORM definitions

With the object-relational mapping is object-oriented software development methods and the development generated. Object-oriented development approach is to mainstream development approach today's enterprise-class application development environment, a relational database is the main data storage system enterprise application environments permanent storage of data. Object and relational data are two forms of business entities in the form of business entity performance object in memory, the performance of relational data in the database. An association and inheritance relationships between objects in memory, and in the database, relational data can not be directly expressed many to many associations and inheritance. Accordingly, the object - relational mapping ORM system is generally present in the form of middleware, the main procedures for mapping objects to a relational database data. Is from the mathematical theory developed from two significant differences from the theoretical basic principles of object-oriented software engineering (e.g., coupling, polymerization, package) developed on the basis of the relational database. To solve this mismatch phenomenon, object-relational mapping technology came into being. O / R O originated letter "subject" (Object), and R is derived from "relationship" (Relational). Almost all of the programs inside, there are objects and relational databases. In the business logic and user interface layer, we are object-oriented. When the object information is changed, we need the information objects stored in a relational database. Popular products such as Java ORM of Hibernate, .Net's EntityFormerWork and so on.

ORM benefits

Model module in the MVC framework are included ORM, mainly for developers to bring the following benefits:

  • To achieve a decoupling of the data model and database by simple configuration database can easily be replaced without the need to modify the code.
  • Only object-oriented programming, do not need to write the code for the database.
  • Defined in MVC Model class, by ORM relational database table corresponding to the relationship between the properties of the object reflects the object, this relationship is mapped to the data table.

Creating a demo

Create a virtual environment:

python -m venv env

Execution env \ activate in Scripts directory, enter the virtual environment

E:\python-projects\django_second_day\env\Scripts\activate

In a virtual environment, install django, installation mysqlclient

python -m pip install django
pip install mysqlclient

Create a Django project

django-admin startproject django_second_day

Open the settings.py file under django_second_day directory to find DATABASES item, use the default database is SQLites3

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

Modify the database is MySQL database

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_second_day', #数据库名字,
        'USER': 'root', #数据库登录用户名
        'PASSWORD': '123456', #数据库登录密码
        'HOST': 'localhost', #数据库所在主机
        'PORT': '3306', #数据库端口
    }
}

Note that the database need to manually create our own good, we returned to the project root directory, create an application bookapp

python manage.py startapp bookapp

Then we will bookapp registered to the project, in settings.py file, add to your INSTALLED_APPS

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

Define model classes

Model type applications are defined in models.py file application folder, such as our model class definition should be in the "bookapp / models.py" file. Keep in mind that the Model class model class must be inherited from django.db.models in. We define two classes, a class library, class represents a character in the book's characters.

from django.db import models

# Create your models here.

# 图书类Book
class Book(models.Model):
    name = models.CharField(max_length=32)
    pub_date = models.DateField()
    read_num = models.IntegerField(default=0)
    isDelete = models.BooleanField(default=False)


# 人物类
class Human(models.Model):
    name = models.CharField(max_length=32)
    gender = models.BooleanField(default=True)
    # 人物简介
    comment = models.CharField(max_length=512)
    # 图书,人物和图书的关系定义为图书1:n人物
    book = models.ForeignKey('Book', on_delete=models.CASCADE)
    isDelete = models.BooleanField(default=False)

And then generate the migration file, perform the migration

python manage.py makemigrations
python manage.py  migrate

So that our data sheet has been established, and table names are bookapp_book bookapp_human.

Add a few table data.

INSERT INTO bookapp_book(NAME,pub_date,read_num,isDelete) VALUES
('射雕英雄传','1981-1-1',12,0),
('天龙八部','1976-7-23',36,0),
('倚天屠龙记','1998-11-2',20,0),
('鹿鼎记','1955-12-12',58,0);

INSERT INTO bookapp_human(NAME,gender,book_id,COMMENT,isDelete) VALUES
('郭靖',1,1,'降龙十八掌',0),
('黄蓉',0,1,'打狗棍法',0),
('黄药师',1,1,'弹指神通',0),
('欧阳锋',1,1,'蛤蟆功',0),
('乔峰',1,2,'降龙十八掌',0),
('段誉',1,2,'六脉神剑',0),
('虚竹',1,2,'天山六阳掌',0),
('王语嫣',0,2,'神仙姐姐',0),
('张无忌',1,3,'九阳神功',0),
('赵敏',0,3,'郡主',0),
('谢逊',1,3,'七伤拳',0),
('张三丰',1,3,'太极拳',0),
('康熙',1,4,'钱',0),
('韦小宝',1,4,'抓奶龙抓手',0);

Custom View, open bookapp / views.py and editing.

from django.shortcuts import render, redirect
from bookapp.models import *
from datetime import date

# Create your views here.

# 首页查询所有图书并返回
def index(request):
    book_list = Book.objects.all()
    return render(request, 'bookapp/index.html', {'list': book_list})

# 创建新图书
def save(request):
    book = Book()
    book.name = '龙珠'
    book.pub_date = date(1986,12,2)
    book.save()
    return redirect('/bookapp')

# 逻辑删除图书
def delete(request, id):
    book = Book.objects.get(id=int(id))
    book.delete()
    return redirect('/bookapp')

Creating templates / bookapp folder in the root directory, then create index.html in bookapp inside.

<!DOCTYPE html>
<html lang="utf-8">
    <head>
        <title>书</title>
    </head>
    <body>
        <a href="/bookapp/save/">新增</a>
        <ul>
            {% for book in list %}
            <li>书名:{{book.name}}  <a href="/bookapp/delete{{book.id}}/">删除</a></li>
            {% endfor %}
        </ul>
    </body>
</html>

Creating urls.py In bookapp, configure the url below.

from django.urls import path, re_path
from . import views

urlpatterns = [
	path('', views.index, name='index'),
    path('save/', views.save, name='save'),
    re_path(r'^delete(\d+)/$',views.delete,name='delete'),
]

urls.py. under the modified django_second_day directory

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('bookapp/', include('bookapp.urls')),
]

Enter the console python manage.py runserverserver is running. Browser access localhost:8000/bookapp, so a small demo is complete.

Defined attributes

Django will create model classes we created a default primary key column automatically increase ideach model class can have only one primary key column, if you use the option to set an attribute as the primary key of this table, then Django will not create a default primary key.

Property naming restrictions:

  • You can not use Python reserved keywords
  • Do not allow the use of a continuous underscore, which is determined by the way Django's query
  • It is specified when the field type defined attribute, specified by the option type field parameters, for example:
属性 = models.字段类型(选项)

Field Type

Field Type meaning
AutoField Automatic growth IntegerField, is the automatic growth of integers, typically do not need, Django will automatically create a property called id attribute grow automatically when you do not specify
booleanField Boolean type fields, True or False
NullBooleanField Three values, Null, True, False
CharField (max_length = character length) String parameter is the maximum length of
TextField Large text fields
IntegerField Integer
DecimalField(max_digits=None, decimal_places=None) Decimal floating point, the first parameter is the total number of bits, the second finger decimals
FloatField Float
DateField[auto_now=False, auto_now_add=False])) Date, auto_now indicate each time an object saved is automatically saved to the current time, for updated timestamp, always points to the last modification time, which is the current time, the default is false, auto_now_add represents the time when the object is created after saving created , which is the time when first created, the time stamp is used to create always points to the current time, the default is false. Note that two parameters are not the same is true
TimeField The same time, parameters and DateField
DateTimeField Date and time, the same parameters and DateField
FileField Files, uploading files field
ImageField Inherited from FileField, to verify the content uploaded to ensure a valid image

Options

Options meaning
null True to allow for the empty, the default value is False
blank True to allow for the field is empty, the default value is False
The difference is more than null is a conceptual database categories, blank form validation concept Category
db_column Name of the field is not specified, use the property name
db_index True indicates that this field is created in the index table, the default value is False
default Defaults
primary_key True indicates that the field is the primary key, the default is False, generally for use AutoField options
unique True to indicate this field must be unique, the default is False

Be modified in two classes bookapp / models.py code is as follows

from django.db import models

# Create your models here.

# 图书类Book
class Book(models.Model):
    # 添加db_column选项,修改数据库字段名为title
    name = models.CharField(max_length=32, db_column="title")
    pub_date = models.DateField()
    read_num = models.IntegerField(default=0)
    isDelete = models.BooleanField(default=False)


# 人物类
class Human(models.Model):
    name = models.CharField(max_length=32)
    # 设置数据库字段为sex
    gender = models.BooleanField(default=True, db_column="sex")
    # 人物简介,null数据库字段允许为空,blank是指输入框不能为空
    comment = models.CharField(max_length=512, null=True, blank=False)
    # 图书,人物和图书的关系定义为图书1:n人物
    book = models.ForeignKey('Book', on_delete=models.CASCADE)
    isDelete = models.BooleanField(default=False)

Generate migration file, and then perform the migration. View the contents of a database field changes.

Field inquiries

Next, add the following configuration in settings.py file for sql statement printed in the console

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        },
    },

    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level': 'DEBUG',
        },
    }
}

In Django query conditions can be accomplished by calling a number of methods, such as filter (), syntax exclude (), get () and other methods, the parameters are as follows

属性名称__比较运算符=值

Description: There are two underscore and comparison between the attribute name, the attribute name can not contain consecutive underscores.

Conditional operator

Equal use exact, such as querying No. 1 book

book = Book.objects.filter(id__exact=1)
简化为
book = Book.objects.fiter(id=1)

Fuzzy query using the contains, contains

book = Book.objects.filter(title__contains='雕')

If you include%, no escape, directly.

... to the beginning or end startswith, endswith: beginning with a specified value or end

book = Book.objects.filter(title__startswith='射')

Above are case sensitive operators, these operators together before i represents a case insensitive, such as iexact, icontains, istartswith, iendswith.
Empty query isnull: is null.

book = Book.objects.filter(title__isnull=False)

Range queries in: whether or not included in the scope.

book = Book.objects.filter(in__in=[1,2,3])

Comparative query gt, gte, lt, lte: greater than, greater equal, less than, or less.
Query id than or equal to 2 books

book = Book.objects.filter(id__gte=2)

Is not equal to the use of the exclude () filter.
Query id not equal to the book of 1

book = Book.objects.exclude(id=1)

Date inquiry year, month, day, week_day, hour, minute, second: the date and time for the type of property is operated.
Queries in 1981 published the book.

book = Book.objects.filter(pub_date__year=1981)

Query after 1 May 1985 published work

book = Book.objects.filter(pub_date__gt=date(1985, 5, 1))

Note: filter () method returns the query set, the result is the contents [] value in the list, the get () method returns a single result.

F object

Compared with the previous constant value attribute queries are objects, and objects using django.db.models.F compare the two properties. The syntax is as follows:

F(属性名)

For example, the query id is less than the amount of reading books

book = Book.objects.filter(id__lt=F('read_num'))

Q objects

A plurality of filters and individually represent a logical relationship between calls, equivalent and.
Queries reading greater than 30, and a name like "Dragon" book

book = Book.objects.filter(read_num__gt=30, title__contains='龙')
或
book = Book.objects.filter(read_num__gt=30).filter(title__contains='龙')

Or OR logic of the query needs django.db.models.Q () target binding | operator implementation. grammar:

Q(属性名__运算符=值)

Query name like "Dragon" or "British" book

book = Book.objects.filter(Q(title__contains="龙") | Q(title__contains="英"))

Logic may also be used and in fact Q () object implementation, an operator & need to be used.
Queries reading greater than 30, and a name like "Dragon" book

book = Book.objects.filter(Q(read_num__gt=30) & Q(title__contains='龙'))

Non-use of ~ operator.
Query number is not equal to the book of 1

book = Book.objects.filter(~Q(id=1))

Aggregate function

Use Aggregate () call to the filter aggregate function, Avg, Count, Max, Min , Sum, are as defined in the django.db.models.
Discover all books titles

book = Book.objects.aggregate(Count('id'))

In this case, the return value is an Aggregate type dictionary, the following format:

{'属性名__聚合类小写': 值}
比如上述
{'id__count': 4}

In fact, using the count Aggregate generally not used () filter, but in the following manner, it returns a number

book_num = Book.objects.count()

Querysets

There just mentioned, filter () method returns a query value is set, then what is the query set it? It represents a set of queries obtained from the database and the object set, the method returns some filters query set, the meaning of the query set can be zero, one or more filters. Filters limit the results of the query based on the given parameters from Sql perspective, the query set is equivalent to the result of the select statement, the filter is a restriction, and where similar clauses limit.

Return filter query set:

  • all (): returns all data
  • filter (): returns the data satisfies the conditions
  • exclude (): returns the data other than the condition, corresponding to portions where the sql statement not keywords
  • order_by (): to sort the results

Return a single value of the filter:

  • get (): returns the object satisfies a condition of a single
    • If you do not find the cause "model class .DoesNotExist" abnormal
    • If more than one is returned, it will lead to "model class .MultipleObjects.Returned" abnormal
  • count (): Returns the total number of the current query results.
  • aggregate (): polymerization, returns a dictionary.

Determine whether there is a set of query data: exist () method to determine whether a data query set, if it returns True, otherwise False.

Two characteristics

  1. Inert perform: Create a query set does not access the database until you call data, will access the database, call the methods are iterative data, serialization, used in conjunction with if.
  2. Cache: Use the same set of query, the query to the database will first use, then cache the result, it will use the cached data when the second call.

Limit the query set

May be removed or slice a standard query set, is equivalent to the limit and offset sql clauses. It does not support negative indexes. After the return of the query set to slice a new set of queries, the query will not be executed immediately. If the acquisition of an object, directly [0] is equivalent to [0: 1] .get (), but if there is no data, [0] IndexError initiator exception, [0: 1] .get () if no data is abnormal initiator DoesNotExist .

Relational model class

Relationship relational database comprising three, one-one, many-type field in the corresponding Django follows:

  • ForeignKey: many, this field should be defined in many end.
  • ManytoManyField: many to many, the field definitions at either end.
  • OneToOneField: one, the field definitions at either end.

Related inquiries

Django realize associated query, there are two ways, one is through the object relational query execution, one is through the implementation of the model class associated with the query.

Object relational query execution by

When you define a model class, you can specify one of three associations, the most common time-to-many relationship, this time written "books - people" as-many relationship. Accessed by one or more access syntax:

1 的一方模型类.多对应的一方模型类名小写_set
也就是:
book = Book.objects.get(id=1)
book.human_set.all()

In turn, by the multi-party access to a party syntax:

直接使用多对应的模型类对象.该模型类中关系类的属性名称
human = Human.objects.get(id=1)
human.book

Access a corresponding model class associated object id syntax:

多对应的模型类对象.关联类属性_id
human = Human.objects.get(id=1)
human.book_id

By model class associated with the query execution

Query a data model class by a multi-model class conditions, the following syntax

关联模型类名小写__属性名__条件运算符=值

Note: You can not fill portion __ conditional operators, it represents equal, and the results of the inner join same sql

Query is associated with the name of "Guo", the hero of the book

books = Book.objects.filter(human__name__contains='郭')

By a model class multi-criteria query data model classes, syntax is as follows

一模型类在多对应的模型类中关联属性名__一模型类中的属性__条件运算符=值

People inquire the corresponding book titles containing "Dragon" in

human = Human.objects.filter(book__title__contains='天龙')

Autocorrelation

For three provinces directory, this type of data, similar to the table structure, and the data is limited, we can set the associated data from the table, the main key field associated with this table. Area can define a class.

# 定义用于表示地区的类,存储省、市、区三级目录信息
class Area(models.Model):
	# 名称
	name=models.CharField(max_length=32)
	# 父级id
	parent=models.ForeignKey('self', null=True, blank=True)

Perform the migration

python manage.py makemigrations
ython manage.py migrate

We write a template for the information on the page display area

<!DOCTYPE html>
<html lang="utf-8">

<head>
    <title>area信息</title>
</head>

<body>
    当前地区:{{area.name}}
    <hr />
    上级地区:{{area.parent.name}}
    <hr />
    下级地区:
    <ul>
        {%for a in area.area_set.all%}
        <li>{{a.name}}</li>
        {%endfor%}
    </ul>
</body>

</html>

Add area method in the views.py

def area(request):
    area = Area.objects.get(id=2)
    return render(request, 'bookapp/area.html', {'area': area})

Configuring the url in urls.py

path('area/', views.area, name='area')

Add a few data in the database

INSERT INTO `django_second_day`.`bookapp_area`(`id`,`name`,`parent_id`) VALUES ( '1','黑龙江',NULL);
INSERT INTO `django_second_day`.`bookapp_area`(`id`,`name`,`parent_id`) VALUES ( '2','哈尔滨市',NULL);
INSERT INTO `django_second_day`.`bookapp_area`(`id`,`name`,`parent_id`) VALUES ( '3','平房区','2');
INSERT INTO `django_second_day`.`bookapp_area`(`id`,`name`,`parent_id`) VALUES ( '4','南岗区','2');
INSERT INTO `django_second_day`.`bookapp_area`(`id`,`name`,`parent_id`) VALUES ( '5','佳木斯市','1');

A web browser.

http://localhost:8000/bookapp/area/

You can see related information from the display on the page.

Examples of the method class model

  • str (): when the object into a string will be called.
  • save (): class object model is saved into the data table, ORM frame is automatically converted to the corresponding insert or update statement.
  • delete (): The model object is removed from the data table, ORM framework into corresponding delete statement.

Model class properties

objects: Manager, models.Manager object type for interacting with the database. When there is no model class definition manager, Django generates a manager named objects for each model class, the custom manager, Django default manager objects are no longer generated.

Book class defines the model manager book_manager syntax is as follows:

class Book(models.Model):
	...
	book_manager = models.Manager()

Manager Manager

Django model manager is an interface database operation, each model class Django application have at least one manager. Django supports custom management class, inherited from models.Manager.

Custom manager class is primarily used in two cases:

  • Modify the original query set, rewrite all () method
  • The method manager to add additional classes, such as inserting data into the database.
  1. Modify the original query set, rewrite all () method.

Open bookapp / models.py file, define BookManager

# 图书类管理器
class BookManager(models.Manager):
	def all(self):
		# 查询没有被删除的图书信息,重写 all() 方法
		return super().all().filter(isDelete=False)

Manager defined in the model class Book

class Book(models.Model):
    ...
    books = BookManager()
  1. Add add_book method in Manager
class BookManager(models.Manager):
    ...
    #创建模型类对象,接收要添加的信息
    def add_book(self, title, pub_date):
        #创建模型类对象self.model可以获得模型类
        book = self.model()
        book.title = title
        book.pub_date = pub_date
        book.read=0
        book.isDelete = False
        # 将数据插入进数据表
        book.save()
        return book

Called by

book=Book.books.add_book("add", date(2001,1,1))

Yuan Options

Model class definition of class Meta, for setting meta information, such as the use of self db_table name definition table.

The default name of the table is:

<app_name>_<model_name>
例:
bookapp_book

We modify the generated data model class Book table named Book, add the following in the Book model class, as follows

class Book(models.Model):
	...
	# 定义元选项
	class Meta:
		db_table='book'

Epilogue

This content written off for several days, but also to step up to learn!
If you find my articles where there is an error or have any good ideas can contact me, we study together progress together, my email address is [email protected]

let’s do more of those!

Published 26 original articles · won praise 2 · Views 2334

Guess you like

Origin blog.csdn.net/qq_42909545/article/details/103375107