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

[experience sharing] summary of database operations commonly used in Django development

編輯:Python

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/False

Use 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

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