ORM operations

ORM operation

    General Operation

      It will be part:

  1.all ()  to query all the results, the final result is QuerySet object.

models.Press.objects.all()  # 查询所有出版社

  2.values (* field)  Returns a ValueQuerySet - a special QuerySet, obtained after running the model does not instantiate the object of a series. But a dictionary can be iterative sequence. Simply put, it is ValueQuerySet list contains the query to the results of each result is a dictionary, the dictionary is the key field field, is found in the results. When the time field does not write the query to all fields.

models.Press.objects.all().values()  # 查询所有对形象的所有字段,每条记录为一个字典

models.Press.objects.all().values('id', 'name')  # 查询所有对象的id和name字段,每条记录为一个字典

  3.values_list (* field)  and values () are very similar, the difference is that he is a return to the ancestral sequence.

models.Press.objects.all().values_list()  # 查询所有对形象的所有字段,每条记录为一个元祖,顺序为values_list()中填写的字段的顺序

models.Press.objects.all().values_list('id', 'name')  # 查询所有对象的id和name字段,每条记录为一个元祖,顺序为values_list()中填写的字段的顺序

4. Add Data

A:添加一条数据:
models.UserInfo.objects.create(name='lxx',age=23, ut_id=2)
B:创建一个字典添加数据:
  dict = {"name":'xxx', 'age':23, 'ut_id':3}
models.UserInfo.objects.create(**dict)
 
添加多条数据:
  info = [
        models.UserInfo(name='root1', age=34, ut_id=1),
        models.UserInfo(name='root2', age=35, ut_id=2),
        models.UserInfo(name='root3', age=36, ut_id=1),
        models.UserInfo(name='root4', age=37, ut_id=3),
        models.UserInfo(name='root5', age=32, ut_id=1),
    ]
  
 models.UserInfo.objects.bulk_create(info)

5. Delete Data

models.Userinfo.objects.filter(id=3).delete()

6. Update Data

models.UserInfo.objects.filter(id=3).update(name='lll', age=23)

7. Forward inquiry

查询所有用户的用户类型
    res = models.UserInfo.objects.all()
    for obj in res:
        print(obj.name, obj.age, obj.ut.title)

8. Reverse Lookup

res = models.UserType.objects.all()
    for obj in res:
        #### 表名小写_set
        # print(obj.title, obj.userinfo_set.all())
        #### releate_name的方式
        print(obj.title, obj.users.all())

    ORM query usage Daquan

1. Filter field name

1.__gt. greater than  大于
ret = models.Person.objects.filter(id__gt=1)  # 查询id大于1的所有对象
2.__gte. greater than equal  大于等于
ret = models.Person.objects.filter(id__gte=1)  # 查询id大于等于1的所有对象
3.__lt .less than  小于
ret = models.Person.objects.filter(id__lt=4)  # 查询id小于4的所有对象
4.__lte.less than equal  小于等于
ret = models.Person.objects.filter(id__lte=1)  # 查询id小于等于1的所有对象

** 2. Field name __in ------ (in) **

ret = models.Person.objects.filter(id__in=[1, 3])  # 查询id在列表里的所有对象

  ** 3.exclude (** kwargs) ------ (not in) ** It contains all the objects and filter criteria given do not match, the final result is a QuerySet object.

models.Press.objects.exclude(id=1)  # 查询id不等于1的所有出版社

  ** 4.get (** kwargs) ** returns the object with the given filter criteria to match the returns only one result, if the objects that meet the filter criteria of more than one or none, will throw an error. The end result is an object .

models.Press.objects.get(id=1)  # 查询id等于1的出版社

  ** 5. Field Name __range = [Condition 1, Condition 2] is equivalent to the field name gte = 1 condition, the field name lte = Condition 2, wherein the comma (,) and represents the relationship. [Condition 1, Condition 2] of closed interval .-------- (and the BETWEEN ...) **

ret = models.Person.objects.filter(id__gte=1, id__lte=3)  # 查询id大于等于1,小于等于3的所有对象

ret = models.Person.objects.filter(id__range=[1, 3])  # 查询id在1到3之间的所有对象

​ **6.__startwith--__endswith--__contain-------(like)

##### where name like 'like%'
    ##### g:全局 global  i: ignore (忽略大小写)
    res = models.UserInfo.objects.filter(name__startswith="ze")
    res = models.UserInfo.objects.filter(name__istartswith="zekai")

    ##### where name like '%kk'
    res = models.UserInfo.objects.filter(name__endswith="kkk")
    res = models.UserInfo.objects.filter(name__iendswith="jjj")
    ##### where name like '%hhh%'
    res = models.UserInfo.objects.filter(name__contains='hhh')
    res = models.UserInfo.objects.filter(name__icontains='ggg')

    ###正则
    res = models.UserInfo.objects.filter(name__regex="^zekai$")

7.count Returns the number of database queries matching (QuerySet) objects.

        #### select count(*) from userinfo where id>3;
    #### select count(id) from userinfo where id>3;
    res = models.UserInfo.objects.filter(id__gt=3).count()

  8.order_by (* field)  to sort the final results of the query result set QuerySet object to the * field when a minus sign in front. (-), the descending order.

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

1 models.Press.objects.all().order_by('-id')  # 查询结果按照id降序排列.结果为QuerySet对象.
2 models.Press.objects.all().order_by('age','-id')  # 查询结果先按照age字段增序排列,出现相同age时再按照id降序排列.结果为QuerySet对象.

9.group by


        ### select id, sum(age) as s, username from userinfo group by username
    from django.db.models import Count, Min, Max, Sum
    res = models.UserInfo.objects.values("name").annotate(s=Sum('age'))
    print(res.query)

    ### select id, sum(age) as s, username from userinfo group by username having s > 50;
    res = models.UserInfo.objects.values("name").annotate(s=Sum('age')).filter(s__gt=50)

10.limit

 ##### limit 0, 10 分页
    res = models.UserInfo.objects.all()[1:4]
    # print(res)

 

11.first ()  returns the first record (target), must be to use the first results are returned to QuerySet ()

models.Person.objects.all().first()

  12.last ()  returns the most one record (target), must be to use the last results are returned to QuerySet ()

models.Person.objects.all().last()

13.only

res = models.UserInfo.objects.only('name')

14.defer - exclude this information outside

res = models.UserInfo.objects.defer('id')

15.Q ----- (or) or

from django.db.models import Q
    res = models.UserInfo.objects.filter( Q(Q(id__gt=3) | Q(name='zekai')) & Q(age=23) )

16.F ---- circulation increase

 from django.db.models import F
    models.UserInfo.objects.update(name=F('name')+1)

Sql 17. native similar pymysql

from django.db import connection, connections
    cursor = connection.cursor()  # cursor = connections['default'].cursor()
    cursor.execute("""SELECT * from auth_user where id = %s""", [1])
    row = cursor.fetchone()
    print(row)

  18.distinct ()  eliminate duplicate records (if you query across multiple tables, may be obtained from the returned results in the calculation of QuerySet repeatable results. At this point you can use distinct (), note that only supported by fields deduplication in PostgreSQL. ), returns the result as a QuerySet object.

 models.UserInfo.objects.values("name", 'age').distinct('name')

    print(res.query)  ### 查看上述代码生成的sql语句

  19.exists ()  if QuerySet contains data, returns True, otherwise False.

models.Person.objects.all().exists()

  20.reverse ()  to sort query results in reverse order, note the reverse () usually only have to call on a defined sort QuerySet (order_by specified in the Meta model class () or call ordering method.)

models.Person.objects.all().reverse()

Guess you like

Origin www.cnblogs.com/zhuyuanying123--/p/11354258.html