django-orm框架表单的增删改查

08.14自我总结

django-orm框架

一.orm基本配置

1.创建django项目

  • 命令行:cmd先去到django创建目录,然后输入django-admin startproject django项目名称
  • pycharm就直接创建新project选择django

2.settings.py文件配置

1.需要在install_app中配置需要连接的app

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app_mysql.apps.AppMysqlConfig', #这个是我们pycharm创建时候自动帮我们注册的就是app配置
    'app_mysql', #如果有新的或者命令行创建的app我们只要这这里面把app名称写上去即可
]

2. 需要在database中进行配置连接mysql的用户名和密码以及数据库

DATABASES = {
    'default':{
        'ENGINE':'django.db.backends.sqlite3',  #sqlite3数据库是个小型的数据库
        'NAME':os.path.join(BASE_DIR,'sqlite3') #NAME填写路径即可
    }
    # 'default': {
    #     'ENGINE': 'django.db.backends.mysql',
    #     'NAME':'库名',
    #     'USER':'mysql账号名称',
    #     'PASSWORD':'mysql密码',
    #     'HOST':'127.0.0.1',
    # }
}

3.__init__的配置

import pymysql
pymysql.install_as_MySQLdb()

4.modelse文件配置

配置表单信息

from django.db import models

# Create your models here.
class sb(models.Model):
    ### 主键自增id不用写, 默认会加上
    name = models.CharField(max_length=30,null=True)

class big_sb(models.Model):
    name = models.CharField(max_length=30, null=True)
    bigsb = models.ForeignKey('sb',id) 


class sb2(models.Model):
    name = models.CharField(max_length=30,null=True)

5.生成表单语句

在命令行进行操作

  • python manage.py makemigrations
  • python manmge.py migrate

二.orm框架的表单的增删改查

必须先在逻辑业务层中载入

from 表单所在的app名称 import models

其中表名均为再modelse中配置的表的名称

1.增

  • 单条数据:

    • 方法一 : models.表名.objects.create(字段1=值1,字段2=值2........)
    • 方法二:dict = {'字段1':值,'字段2':值.........};models.表名.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)
    

2.删

models.表名.objects.filter(满足的条件).delete()

3.改

models.表名.objects.filter(满足的条件).update(name='lll', age=23)

4.查

models.UserType.objects.all().values()

表A的ud关联表b

有子健关系的查询正向查询通过A表中的ud查到表b的id

  • 方法一:models.A.objects.all().values('ud__id')

  • 方法二

    res = models.A.objects.all()
    for a in res:
        print(a.ud.id)
    

有子健关系的查询返向查询通过b表中的查到a表ID

  • 方法一:models.B.objects.all().values('A__id')

  • 方法二:

    res = models.B.objects.all()
    for b in res:
        print(b.a_set.id) #### 表名小写_set
    

三.orm进阶查询

1.字段名过滤

filter满足条件的

exclude不满足条件

用法:

#id等于3的
models.表名.objects.filter(id=3).values()

#id不等于3的
models.表名.objects.exclude(id=3).values()

关于filter与exclude里面填写的参数

  • 等于:字段名=值

  • 大于:字段名__gt=值

  • 大于等于:字段名__gte=值

  • 小于:字段名__lt=值

  • 小于等于:字段名__lte=值

2.成员in not in

res = models.表名.objects.filter(字段名__in=[2,4,5]) # where id in (2,4,5)
res = models.表名.objects.exclude(字段名__in=[1,2]) # where id not in (1,2)

3.区间between...and

# where id between 4 and 8   [4,8]
res = models.表名.objects.filter(字段名__range=[4,8])

4.模糊查询like

# where name like 'a%'
res = models.表名.objects.filter(字段名__startswith="a")
res = models.表名.objects.filter(字段名__istartswith="a") #忽略大小写

# where name like '%a'
res = models.表名.objects.filter(字段名__endswith="a")
res = models.表名.objects.filter(字段名__iendswith="a") #忽略大小写

# where name like '%a%'
res = models.表名.objects.filter(字段名__contains="a")
res = models.表名.objects.filter(字段名__icontains="a") #忽略大小写

只要是i开头的基本上都是忽略大小写

5.数据条数count

# select count(*) from userinfo where id>3;
# select count(id) from userinfo where id>3;
#用sql语句查询数据条数尽量不要查count(*)查主键会快很多
res = models.UserInfo.objects.filter(id__gt=3).count()

6.排序order by

#升序
res = models.表名.objects.order_by('字段名称')

#降序
res = models.表名.objects.order_by('-字段名称')

#多个条件进行排序
res = models.表名.objects.order_by('字段1','字段2') #当字段1相同是会更具字段2进行排序

7.分组group by已经having

# 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'))

# 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)

8.分页limit

# limit 1, 3 分页
res = models.UserInfo.objects.all()[1:4]
#因为获取对象是列表所有切片即可

9.last/first

第一条:res = models.表名.objects.first()

最后一条:res = models.表名.objects.last()

10.only|defer

只查某个字段:only('字段名称')

除某个字段以外的所有字段:defer('字段名')

注意:主键id不管怎么样都会查

12.and|or

只有and

#id等于3and名字等于a
models.表名.objects.filter(id=3,and name='a').values()

只有or

# Q
from django.db.models import Q
res = models.UserInfo.objects.filter(Q(id__gt=3) | Q(name='zekai')) #or用|链接

有and和or

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

13.F

from django.db.models import F
models.UserInfo.objects.update(name=F('name')+1) #字段名称都加1

14.原生sql 类似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)

15.去重distinct

models.UserInfo.objects.values("name", 'age').distinct() #前面values有多少个就对多少个值进行去除

四.补充一个小点

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

posted @ 2019-08-14 17:05  小小咸鱼YwY  阅读(709)  评论(0编辑  收藏  举报