当前位置:网站首页>[experience sharing] summary of database operations commonly used in Django development
[experience sharing] summary of database operations commonly used in Django development
2022-06-28 13:39:00 【Tencent blue whale assistant】
Query class operation
1) Query all results , Quite a sql Medium select * from
list = Test.objects.all()
2) Conditions of the query ,filter relevant sql Medium where, Used to filter query results
Pass multiple parameters :result = Test.objects.filter(id=1, name=’test’)
If multiple conditions and queries , Directly separated by commas ,filter The arguments in the function are Test Model In the field
3) Get single object ,get Method parameters are generally Model Primary key of , If you can't find it, you will report an error
test_obj = Test.objects.get(id=1)
4) Limit the amount of result data returned , amount to sql Medium limit, among order_by Yes for sorting , If according to the field a Reverse sort , Namely order_by(“-time”)
Test.objects.order_by('name')[0:2]
5) Chain query
Test.objects.filter(name=’test’).order_by(“-ctime”)
6) Multi condition parameter query , A dictionary , Construct query conditions
data = Test.objects.filter(**query_dict).order_by(“-ctime”).values
among query_dict For a dictionary ,key Is a condition field ,value Is the condition value
query_dict = {'id':123,'name':’yyp’}
7) Pass on Q object , Construct query conditions
- stay filter() The keyword parameters in the equivalent function are all “and” Relationship . But to execute more complex queries ( such as , Implement the filter criteria or Relationship ), have access to Q object .
- Q Objects include AND Relationship and OR Relationship
- Q Objects can be used & and | Operator to connect . When an operation connects two Q Object time , A new equivalent Q object
1、 First step , structure Q object :
fromdjango.db.models import Q
Q(name__startswith=’h’) | Q(name__startswith=’p’)
2、 The second step ,Q Object is used as a query parameter , Multiple Q The object is and Relationship :
Test.objects.filter(
Q(date=’2018-10-10 00:00:00’),
Q(name__startswith=’h’) | Q(name__startswith=’p’)
filter() And so on Q Object and condition parameters , but Q The object must precede the condition parameter
8) Filter operations that do not meet the conditions
data = Test.objects.exclude(id=1)
Pass in condition query
q1 = Q()
q1.connector = 'OR' # How to connect
q1.children.append(('id', 1))
q1.children.append(('id', 2))
q1.children.append(('id', 3))
models.Tb1.objects.filter(q1)Merge condition query
con = Q()
q1 = Q()
q1.connector = 'OR'
q1.children.append(('id', 1))
q1.children.append(('id', 2))
q1.children.append(('id', 3))
q2 = Q()
q2.connector = 'OR'
q2.children.append(('status', ' On-line '))
con.add(q1, 'AND')
con.add(q2, 'AND')
models.Tb1.objects.filter(con)Add class operation
1) Add a record
test1 = Test(name=’yyp’)
test1.save()
Update class operations
1) First query to get the object , Then modify the value of the object , Save again
test1 = Test.objects.get(id=1)
test1.name = ‘Google’
test1.save()
2) Conditional chain update
Test.objects.filter(id=1).update(name=‘Google’)
Delete class operation
1) First query to get the object to be deleted , And then directly delete operation
// Delete id=1 The data of
test1 = Test.objects.get(id=1)
test1.delete()
2) Conditions delete
Test.objects.filter(id=1).delete()
QuerySet relevant
Django in model The structure type queried is QuerySet, It is essentially a set of query objects .
1) Convert multiple query results into dictionary lists
// all() Method to query QuerySet, use values Method to a dictionary set
data= Test.objects.all().values()
data_dict_list = list(data)
<QuerySet [<Test: test>]> ----><QuerySet [{“id”:XXX, “name”:XXX}]>
2)QuerySet Object to dictionary object
fromdjango.forms.models import model_to_dict
data = Test.objects.get(id=1)
data_dict = model_to_dict(data)
3) Serialized into json data
For many web When developing interfaces , To return is json data , and django from DB The query results in a set of objects , You can consider django-rest-framework Library serializers class , For details, please refer to :Tutorial 1: serialize
Summary of query criteria
Field name __op:
__exact Exactly equal to like ‘aaa’
__iexact Precision is equal to ignoring case ilike‘aaa’
__contains contain like ‘%aaa%’
__icontains Include ignore case ilike‘%aaa%’, But for sqlite Come on ,contains The effect is the same as icontains.
__gt Greater than
__gte Greater than or equal to
__lt Less than
__lte Less than or equal to
__in Exist in a list Within the scope of
__startswith With … start
__istartswith With … Ignore case at the beginning
__endswith With … ending
__iendswith With … ending , Ignore case
__range stay … Within the scope of
__year The year of the date field
__month The month of the date field
__day Date of the date field
__isnull=True/FalseUse sql Statement to query
fromdjango.db import connection
cursor = connection.cursor()
cursor.execute(“select * from Test where name = %s”, "yyp")
row = cursor.fetchone()This article is edited and released by Tencent blue whale Zhiyun , Tencent blue whale Zhiyun ( Short for blue whale ) The software system is a set of systems based on PaaS Technology solutions for , Committed to building an industry-leading one-stop automatic operation and maintenance platform . At present, the community version has been launched 、 Enterprise Edition , Welcome to experience .
- Official website :https://bk.tencent.com/
- Download link :https://bk.tencent.com/download/
- Community :https://bk.tencent.com/s-mart/community/question
边栏推荐
- PHP抓取网页获取特定信息
- The difference between align items and align content
- CVPR再起争议:IBM中稿论文被指照搬自己承办竞赛第二名的idea
- Solution to directory access of thinkphp6 multi-level controller
- iNFTnews | 科技巨头加快进军Web3和元宇宙
- Yii2 connects to websocket service to realize that the server actively pushes messages to the client
- How about stock online account opening and account opening process? Is it safe to open a mobile account?
- Hubble数据库x某股份制商业银行:冠字号码管理系统升级,让每一张人民币都有 “身份证”
- Notes on the use of official jeecg components (under update...)
- 为什么越来越多的用户放弃 Swagger,选择Apifox
猜你喜欢

Hubble数据库x某股份制商业银行:冠字号码管理系统升级,让每一张人民币都有 “身份证”

Elastic box auto wrap demo

thinkphp6 多级控制器目录访问解决方法

Kubernetes in-depth understanding of kubernetes (I)

抢做意大利岛主?刘强东两月套现66亿 疑一次性5.6亿“紧急转账”急购欧洲海上皇宫

Kubernetes 深入理解kubernetes(一)

RSLO:自监督激光雷达里程计(实时+高精度,ICRA2022)

2022年中国运维安全产品市场规模及发展趋势预测分析

单元测试 CI/CD

5A synchronous rectifier chip 20V to 12v2a/5v4.5a high current 24W high power synchronous rectifier chip high current step-down IC fs2462
随机推荐
How does Quanzhi v853 chip switch sensors on Tina v85x platform?
StackOverflow 2022数据库年度调查
Oceanwide micro fh511 single chip microcomputer IC scheme small household appliances LED lighting MCU screen printing fh511
Commonly used "redmine" for # test bug
众昂矿业着眼氟化工产业,布局新能源产业链
Inftnews | technology giants accelerate their march into Web3 and metauniverse
Yii2 writing the websocket service of swoole
G1 important configuration parameters and their default values in the garbage collector
《蛤蟆先生去看心里医生》阅读笔记
1015. picking flowers
How to solve the data inconsistency between redis and MySQL?
设计人工智能产品:技术可能性、用户合意性、商业可行性
China Database Technology Conference (DTCC) specially invited experts from Kelan sundb database to share
Google Earth engine (GEE) - Global organic soil area of FAO (1992-2018)
China Radio and television 5g package is coming, lower than the three major operators, but not as low as expected
How fragrant! The most complete list of common shortcut keys for pychar!
Pytorch Foundation
PHP gets the number of digits and replaces it with the specified mantissa
Which company has a low rate for opening a securities account? How to open an account is the safest
Writing skills of resume