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
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)
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)
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)
1) Add a record
test1 = Test(name=’yyp’)
test1.save()
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’)
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()
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
__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
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 .