Django basis of the model layer (models.py), ORM query of single-table queries, multi-table queries and query across tables

Django basis of the model layer (models.py), ORM query of single-table queries, multi-table queries and query across tables

ORM query

If you want to see inside the real orm statement sql statement, there are two ways:

1.如果是queryset对象 那么可以点query直接查看该queryset的内部sql语句
2.在django项目的配置文件中 配置一下参数即可实现所有的orm在查询的时候自动打印对应的sql语句,把下面的代码加到settings配置文件中即可
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level': 'DEBUG',
        },
    }
}

django test environment to build

Manage.py copy four lines of code into the file tests.py file, and then writing two lines of code in the tests.py

tests.py

import os

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Books_Manage_System.settings")
import django
django.setup()
# 就可以在下面测试django任何的py文件

Single-table queries

13 should be aware of methods

13 method
1, all (): check all data, the result is Queryset object, but is inert query, use the time to check the data before the data is displayed, not the case do not investigate
2, filter (): Query is inert the results also Queryset objects, you need to query
3, get (): check the data object itself, does not recommend the use of
4, order_by (): Sort by default in ascending order, plus the negative parentheses condition number is descending
5, reverse (): anti turn: front must go through order_by () to sort the data inversion
6, exclude (): All data except the data meet the conditions of
7, values (): brackets have conditions, the result is Queryset objects, sets a list of dictionaries
8, values_list (): brackets have conditions, the result is Queryset object list set tuples
9, count (): statistics of the number of
10, distinct (): when the data must be completely identical to: de-duplication de-emphasis
11, exists (): determines whether the data exists, returns True or False, with no
12, first (): get the first
13, last (): take the last

As long as the object can be unlimited queryset point queryset object methods

Magical double underline inquiry

# 查询价格大于200的书籍
res = models.Book.objects.filter(price__gt=200)
print(res)

# 查询价格小于200的书籍
res = models.Book.objects.filter(price__lt=200)
print(res)

# 查询价格大于等于200.22的书籍
res = models.Book.objects.filter(price__gte=200.22)
print(res)

# 查询价格小于等于200.22的书籍
res = models.Book.objects.filter(price__lte=200.22)
print(res)

# 查询价格要么是200,要么是300,要么是666.66
res = models.Book.objects.filter(price__in=[200,300,666.66]) # 都包含
print(res)

# 查询价格在200到800之间的
res = models.Book.objects.filter(price__range=(200,800))  # 顾头不顾尾
print(res)
"""原生sql语句:模糊匹配
    like 
        %
        _
"""
# 查询书籍名字中包含p的
res = models.Book.objects.filter(title__contains='p')  # 区分大小写,仅仅只能拿小写p
res1 = models.Book.objects.filter(title__icontains='p')  # 忽略大小写
print(res)
print(res1)
    
# 查询书籍是以三开头的
res = models.Book.objects.filter(title__startswith='三') # 查询以三开头的
res1 = models.Book.objects.filter(title__endswith='P')  # 查询以P结尾的,区分大小写
print(res)
print(res1)

# 查询出版日期是2019年的书籍(******)
res = models.Book.objects.filter(publish_date__year='2019')
print(res)
# 查询出版日期是10月的书籍
res = models.Book.objects.filter(publish_date__month='10')
print(res)

Multi-table query

When writing orm statements, with the write sql statement, do not think a one-time finish, the best point of view to write a little check point

Deletions foreign key field change search

Deletions many fields change search

increase

# 方式一
models.Book.objects.create(title='三国演义', price=123.23, publish_id=1)  # publish_id直接传出版社主键值
# 方式二
publish_obj = models.Book.objects.fliter(pk=2).first()
models.Book.objects.create(title='三国演义', price=123.23, publish=publish_obj)  # publish直接传出版社数据对象

check

book_obj = models.Book.objects.filter(pk=1).first()
print(book_obj.publish)  # 得到该书籍对应的出版社对象
print(book_obj.publish_id)  # 得到该书籍对应的出版社的id

change

# 方式一
models.Book.objects.filter(pk=1).update(publish_id=3)
# 方式二
publish_obj = models.Punlish.filter(pk=2).first()
models.Book.objects.filter(pk=1).update(publish=publish_obj)

delete

models.Publish.objects.filter(pk=3).delete()
# 默认是级联更新、级联删除

Many to many additions and deletions to change search field

Increase relations

add()


book_obj = models.Book.objects.filter(pk=3).first()
print(book_obj.authors)  # 相当于直接跳到了书籍和作者的关系表了
book_obj.authors.add(1)  # 给主键为3的书籍添加主键为1的作者
book_obj.authors.add(2,3) # 给主键为3的书籍添加主键为2和3的作者

author_obj = models.Author.objects.filter(pk=1).first()
author_obj1 = models.Author.objects.filter(pk=2).first()
book_obj.authors.add(author_obj)  # 可以直接添加作者对象
book_obj.authors.add(author_obj,author_obj1)


# add()括号内既可以直接传数字也可以传数据对象,并且支持传多个

Amending,

set()

book_obj = models.Book.objects.filter(pk=3).first()
book_obj.authors.set([3,])

author_obj = models.Author.objects.filter(pk=1).first()
author_obj1 = models.Author.objects.filter(pk=2).first()
book_obj.authors.set(author_obj)  # 可以直接添加作者对象
book_obj.authors.set(author_obj,author_obj1)


# set()括号内既可以直接传数字也可以传数据对象,并且支持传多个,但是要注意括号内必须是可迭代对象

Delete relationship

remove()

book_obj = models.Book.objects.filter(pk=3).first()
book_obj.authors.remove(2)
book_obj.authors.remove(1,2)

author_obj = models.Author.objects.filter(pk=1).first()
author_obj1 = models.Author.objects.filter(pk=2).first()
book_obj.authors.remove(author_obj)  # 可以直接传作者对象
book_obj.authors.remove(author_obj,author_obj1)

# remove()括号内既可以直接传数字也可以传数据对象,并且支持传多个

Clear relationship

clear()

book_obj = models.Book.objects.filter(pk=3).first()
book_obj.authors.clear()

# clear()括号内不需要传任何参数,直接清空当前主键为3的书籍对象的所有记录

ORM cross-table query

1, sub-queries

2, even the table query

The concept of positive and negative

Objects check book publishers, foreign key field in the books, the forward query (have to check the foreign key field is positive)

Press check books, foreign key field in books, reverse lookup (have checked the foreign key field is reversed)

Object-based cross-table queries ----- subqueries

Forward query by field, when the field data corresponding to a plurality of time, and needs .all (), or foreign key field point can direct data objects to get

# 正向查询
# 1、查询书籍是python入门的出版社名称
book_obj = models.Book.objects.filter(title='python入门').first()
# 正向查询按字段
print(book_obj.publish.name)
print(book_obj.publish.addr)

# 2、查询主键是6的书籍的作者姓名
book_obj = models.Book.objects.filter(pk=6).first()
print(book_obj.authors)  # 结果是app01.Author.None
print(book_obj.authors.all())  # 结果是这本书的所有作者的Queryset对象

# 3、查询作者是jason的手机号
author_obj = models.Author.objects.filter(name='jason').first()
print(author_obj.author_detail.phone) # 正向查询按字段
print(author_obj.author_detail.addr)

Reverse lookup table by lowercase, when the result of the query may be a need to add after the table in lowercase _set.all case where a plurality of (); when the result of the query and there is only one case where the lower, need not add anything directly to lowercase table names

# 反向查询
# 4、查询出版社是东方出版社出版过的书籍
publish_obj = models.Publish.objects.filter(name='东方出版社').first()
print(publish_obj.book_set)  # 结果是app01.Book.None
print(publish_obj.book_set.all())  # 加.all()就能拿到该出版社出版的所有书

# 5、查询作者是jason写过的所有书
author_obj = models.Author.objects.filter(name='jason').first()
print(author_obj.book_set.all())

# 6、查询手机号是110的作者
author_detail_obj =  models.AuthorDetail.objects.filter(phone=110).first()
print(author_detail_obj.author)  # 这个拿到作者对象
print(author_detail_obj.author.name) 
print(author_detail_obj.author.age) 

Query ----- even table query based on cross-table double-underlined

# 1、查询书籍是python入门的出版社名称
res = models.Book.objects.filter(title='python入门').values('publish__name')
print(res)  # 正向查询按字段publish查

#2、查询作者是jason的手机号码
# 正向
res1 = models.Author.objects.filter(name='jason').values('author_detail__phone')
print(res1)  # 正向查询按字段查
# 反向
res = models.AuthorDetail.objects.filter(author__name='jason').values('phone')


# 3、查询手机号是120的作者姓名
# 正向
res2 = models.AuthorDetail.objects.filter(phone=120).values('author__name')  # 反向查询按表名小写查
print(res2)
# 反向
res3 =models.Author.objects.filter(author_detail__phone=120).values('name')

# 4、查询出版社是东方出版社出版的书籍名称和出版社地址
res = models.Publish.objects.filter(name='东方出版社').values('book__title','addr')  # 也是反向查询按表名小写


# 5、查询书籍是python入门的作者的手机号(连续跨表查询)
res = models.Book.objects.filter(title='python入门').values('authors__author_detail__phone')
print(res)

Guess you like

Origin www.cnblogs.com/zhuangyl23/p/11735754.html