django orm查询和后端缓存的使用

django orm 查询

1 字段后(db_column='age')
(null=True)#表示数据库里面的该字段数据可以为空
(blank=True)#表示前端表单提交的时候可以为空
(db_index=True)#表示给该字段建立索引
(help_test='这个事说明')#提示说明
(editable=False) #表示这个字段内容不能被编辑
(unique_for_date=True)#表示日期必须唯一
(unique_for_month=True)#表示月份必须唯一
(auto_now_add=True)#自动生成新插入的日期时间
(auto_now=True) # 表示字段信息更新的时间


#浮点型字段中
Decimal=models.DecimalField(max_digits=4,decimal_places=2)#最大长度和小数位数

#外键字段中on_delete
'''
on_delete当一个外检关联的对象被删除时,django将模仿on_delete参数定义的SQL约束执行相应操作
    如下6中操作
    CASCADE:模拟SQL语言中的ON_DELETE CASCADE约束,将定义有外检的模型对象同时删除!(该操作为当前django版本的默认操作)
    SET_NULL:阻止上面的删除操作,但是弹出ProtectedError异常
    SET_DEFAULT:将外检字段设为默认值,只有当字段设置了default参数是,方可使用
    DO_NOTHING:什么也不做
    SET():设置一个传递给SET()的值或者一个回调函数的返回值,注意大小写
'''
2 #定义元数据
class AddressInfo(models.Model):
    assress=models.CharField(max_length=200)
    pid=models.ForeightKey('self',null=True,blank=True,verbose_name='自关联')
    def __str__(self):
        return self.address
    class Meta:#元数据
        
        db_table='cc_address'
        #ordering = ['pid']#根据pid排序
        verbose_name='这是注释'
        verbose_name_plural = verbose_name    
        #abstrace = True #将该模型类设置为一个基类,供其他模型类调用
        #permissions = (('定义好的权限','权限说明'))
        #manage = False
        unique_together = ('address','note') #联合唯一
        #app_labe; = 'customer'#表示该表属于哪个应用
        #db_tablespace #定义数据库表空间的名字
        
    3 #字段的枚举类型 
    
        type=models.CharField(choices=((1,'实战课'),(2,'免费课'),(3,'其他')),max_length=1)
        
        
    4 #设置外键
        #多对一的情况下,在多的表中
        teacher = models.ForeightKey(Teacher,on_delete = models.CASCADE,verbose_name = '课程讲师')#           为了级联删除
        #多对多的情况下,在少的表中
        course=models.ManyToManyField(Course,verbose_name='课程')
    
    5 #数据库同步命令
        (1)生成数据库要执行的内容
        python3 manage.py makemigrations
        (2)执行生成的文件,同步到数据库
        python3 manage.py migrate
    
    6#在模型类中删除一个表格顺序
        (1)删除模型类中的代码
        (2):删除模型类在mogrations下生成的对应文件
        (3):删除django_migrarions对应的生成记录
        (4):删除我们的数据表
            
            
            
            
            
    7 #django数据导入
       (1) 在cmd项目当前目录下执行#python3 manage.py shell
    eg:from customer.models import Teacher
        t = Teacher(nickname='andy')
        t.save()
    (2):通过脚本导入
    (3):python3 manage.py dumpdata>imooc.json#导出数据
        python3 manage.py loaddata imooc.json#导入数据
   
   8 #Models API
    class IndexView(View):
        def get(self,request):
            #1.查询.检索.过滤
            teachers=Teacher.objects.all() #查询集
            teacher2 = Teacher.objects.get(nickname='jack') # get()只能但会一条结果,多条则会报错
            teacher1 = Teacher.objects.filter() #QuerSet,可以多条结果
            for t in teacher3:
                print(f"讲师姓名{t.nickname}--粉丝数{t.fans}")
            #2 字段数据匹配,大小写敏感
            teacher5 = Teacher.objects.filter(nickname__icontains='A')#大小写敏感
            print(teacher5)
            teacher6 = Teacher.objects.all().order_by('-fans')#按照粉丝倒叙排列
            for t in teacher6:
                print(t.fans)
            print(Teacher.objects.filter(fnas__gte=500).order_by('nickname'))
            #4 查看执行的原生SQL
            print(str(xx.query))
            
            
    9 #返回新的QuerySet的API:去重,排序,使用聚合计数,求和,平均数,反向查询
       print(Student.objects.all().exclude(nickname='A同学'))#去除查询结果中nickname='A同学'的数据 
           .exclude#去除某一条符合条件的数据
        .revers()#反向排序--注意:一定要在元数据中写ordering = ['age']
        .extra()#去重
        .defer():#排除一些字段
        .only() # 选择一些字段
       s3 = Student.objects.all().extra(select = {'name':'nickname'})
        for s in s3:
            print(s.name)
       student.objects.all().only('nickname','age').query--值查询执行的两个字段
        (3):values(),values_list 获取字典或者元祖形式的QuerySet
            Teacher.objects.values('nickname','hobby')#字典形式
            Teacher.objects.values_list('nickname','hobby')#元组形式
            Teacher.objects.values_list('nickname',flat=True)#取一条数据的时候,使用flat=Tru可以实现拿到列表
        (4):dates(),datetimes() 根据时间日期获取查询集
            
        (5):union(),intersection(),difference() 并集,交集,差集
            
        (6)select_related() 一对一,多对一查询优化,prefetch_related() 一对多,多对多查询优化;反向查询
        
    (7) .annotate()使用聚合计数,求和,平均数, raw() 执行原生的sql    
        Course.objects.values('teacher').annotate(vol=Sum('volume'))#求和
        Course.objects.values('teacher').annotate(vol=avg('volume'))#求平均值
    
    
    10 不返回queryset的api
    (1)获取对象 get() #不存在或空会报错,get_or_create(),first(),last(),latest(),earliest(),in_bulk()
        print(Course.objects.first())#第一条数据
        print(Course.objects.last())#最后一条数据
        print(Course.objects.earliest())#最近的一条数据
        print(Course.objects.latest())#最老的第一条数据
        print(Course.objects.in_bulk([1,2]))#根据主键的值批量返回对象
    (2)创建对象 create(),bulk_create(),update_or_create() 创建 ,批量创建,更新或创建
    (3)跟新对象,update.update_or_create() #更新,更新或创建
        Course.objects.filter(title='title').update(price=10)
    (4)删除对象 delete() 使用filter过滤
        Course.objects.filter(title='title').delete()
    (5)其他操作exists(),count,aggregate()#判断是否存在,统计个数,聚合
        print(Course.objects.filter(title='title').exists())#查询是否存在,存在返回True,不存在返回False
        print(Course.object.count())#返回记录的个数
        print(Course.objects.aggregate(Max('price'),Min('price'),Avg('price'),Sum('price'))) #查询数据库表格里面的价格的最大,最下,平均值
        
    11 自定义聚合查询
    customer = Cou
    
    12 F对象和Q对象
    from django.db.models import Count,Avg,Min,MAx,Sum,F,Q
    Course.objects.update(price=F('price')-11)#将所有的价格在当前的基础上-11
    Course.objects.filter(volume__lte=F('price')*10) #查询数量小于价格十倍的数据
    print(Course.objects.filter(Q(title__icontains='python')&Q(volume__gte=5000)))#查询名字包含python而且数量大于5000的对象
    print(Course.objects.filter(Q(title__icontains='go')|Q(volume__lte=1000))) #查询标题包含go或者数量小于1000的对象
    结合AND,OR,NOT,|,~,&实现复杂的查询
    
    
    

django的缓存

#在django的settings中,利用redis来做缓存
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        # "LOCATION": "redis://127.0.0.1:6379",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "USER": 'redis',
            "PASSWORD": ":password",
            "SOCKET_CONNECT_TIMEOUT": 10,
            "CONNECTION_POOL_KWARGS": {
                "max_connections": 100,
            },
            # "SERIALIZER": "django_redis.serializers.json.JSONSerializer",
            "DECODE_RESPONSES": True,

        }
    }
}

#在视图中
from django.core.cache import cache
#在接口中
key=''#一个标识,可根据前端传过来的数据判断
if cache.get(key):
    data=cache.get(key)
    return data
#在下面数据准备完成的时候
cache.set(key,data)#设置缓存
cache.expire(key,60*60)#缓存key和时间

linux相关操作

#查看firewalld状态:systemctl status firewalld
#开启防火墙:systemctl status firewalld
#关闭防火墙:systemctl stop firewalld

猜你喜欢

转载自www.cnblogs.com/ouyang99-/p/11744428.html