django ORM CRUD

一.增加数据-Create

  1.类名.objects.create(属性=值,属性=值)

Myomodel.objects.create(name="TeacherCang",age=15)

  2.d={"属性":"值"}     obj=类名(**d)  obj.save()  

d={"name":"Money","age":11}
obj=Myomodel(**d)
obj.save()

  3.obj=类名()  obj.属性=值  obj.save()

obj=Myomodel()
obj.name="Child"
obj.age=9
obj.save()

二.删除数据-Delete

  1.单个删除:类名.objects.get(属性=值).delete()

Myomodel.objects.get(id=8).delete()

  2.批量删除:类名.objects.filter(条件).delete()

Myomodel.objects.filter(age__lt=16).delete()

三.修改数据-Update

  1.单个修改:查  改  存 

obj=Myomodel.objects.get(id=1)
obj.name="xiugai"
obj.save()

  2.批量修改:类名.objects.filter(条件).update(属性=值)

Myomodel.objects.filter(name="money").update(name="amaoagou")

四.查询数据-Retrieve

Myomodel.objects.all()#<QuerySet [<Myomodel: Myomodel object (1)>]>Myomodel.objects.values()#<QuerySet [{'id': 1, 'name': 'xiugai', 'age': 16}]>Myomodel.objects.values('id','age')#<QuerySet [{'id': 1, 'age': 16}]>Myomodel.objects.values_list()#<QuerySet [(1, 'xiugai', 16)]>Myomodel.objects.values_list('name')#<QuerySet [('xiugai',), ('Jerry',)]>Myomodel.objects.filter(name="amaoagou")#<QuerySet [<Myomodel: Myomodel object (10)>]>

  查询:过滤查询:类名.objects.filter(属性__查询谓词=值)#此处是双下划线

  查询谓词:

    1.exact  等值查询

    2.contains  模糊查询,相当于like "%xx%"

    3.in  模糊查询

    4.gt  大于

    5.lt  小于

    6.gte  大于等于

    7.lte  小于等于

    8.startswith  以...开始,相当于like "x%"

    9.endwith  以...结束,相当于like "%x"

    10.range  相当于between and

    11.regex  正则表达式匹配

Myomodel.objects.filter(name__startswith="Kai")#<QuerySet [<Myomodel: Myomodel object (4)>]>Myomodel.objects.filter(name__contains="cher")#<QuerySet [<Myomodel: Myomodel object (9)>]>

  查询:条件取反:类名.objects.exclude(条件)

Myomodel.objects.exclude(name__contains="cher")#<QuerySet [<Myomodel: Myomodel object (1)>]>

  查询:排序查询:类名.objects.order_by(条件)  

    默认是升序,字段名前加“-”即可降序排列

Myomodel.objects.order_by('age').values_list('age')
#<QuerySet [(11,), (11,), (15,), (15,), (16,), (19,), (23,), (36,), (36,)]>Myomodel.objects.order_by('-age').values_list('age')
# < QuerySet[(36,), (36,), (23,), (19,), (16,), (15,), (15,), (11,), (11,)] >Myomodel.objects.order_by('-age','-id').values_list('age','id')
#<QuerySet [(36, 14), (36, 11), (23, 4), (19, 3), (16, 1), (15, 12), (15, 9), (11, 13), (11, 10)]>

  只查询一条:类名.objects.get(条件)

Myomodel.objects.get(id=14)#Myomodel object (14)

  获取查询数量

Myomodel.objects.filter(name="TeacherCang").count()#2

  聚合查询

from django.db.models import Avg,Sum,Count,Max,Min
.........................

Myomodel.objects.aggregate(age=Avg('age'))
Myomodel.objects.aggregate(age=Sum('age'))
Myomodel.objects.aggregate(age=Count('age'))
Myomodel.objects.aggregate(age=Max('age'))
Myomodel.objects.aggregate(age=Min('age'))
posted @ 2019-11-25 21:53  腹肌猿  阅读(174)  评论(0编辑  收藏  举报