• django的数据库操作


    ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中,ORM在业务逻辑层和数据库层之间充当了桥梁的作用。

     

    django的交互式shell

    python manage.py shell

    进入shell后引入相应的models
    from plugin_security.models import Rule

    返回被创建的对象
    Rule.objects.create(plugin_name='ew2o2',plugin_relation='=')
    Rule.objects.create(plugin_name='ew2o')
    或
    obj = models.UserInfo(user=’yangmv’,pwd=’123456′)
    obj.age=32
    obj.save()
    或者
    dic = {‘user’:’yangmv’,’pwd’:’123456′}
    models.UserInfo.objects.create(**dic)
    
    Person.objects.get_or_create(name="WZT", age=23) 这种方法是防止重复很好的方法,但是速度要相对慢些,返回一个元组,第一个为Person对象,第二个为True或False, 新建时返回的是True, 已经存在时返回False.

    Rule.objects.filter(plugin_name__contains='test').delete() 返回被删除的总行数
    或者
    rule=Rule.objects.filter(plugin_name__contains='test')
    rule.delete()

    批量更新,适用于 .all()  .filter()  .exclude() 等后面 (危险操作,正式场合操作务必谨慎)
    修改查到的所有行,返回受影响的行数
    Rule.objects.all().update(plugin_relation='>')
    Rule.objects.filter(id=22).update(plugin_relation='>')
    Rule.objects.all().update(plugin_relation='>',plugin_version='2.2.3')
    Person.objects.filter(name__contains="abc").update(name='xxx') # 名称中包含 "abc"的人 都改成 xxx
    Person.objects.all().delete() # 删除所有 Person 记录
    
    单个 object 更新,适合于 .get(), get_or_create(), update_or_create() 等得到的 obj,和新建很类似。
    
    twz = Author.objects.get(name="WeizhongTu")
    twz.name="WeizhongTu"
    twz.email="tuweizhong@163.com"
    twz.save()  # 最后不要忘了保存!!!
    Job.objects.update_or_create(defaults={'app_name': app_name,'job_name': job_name,'job_git': job_git,'git_branch': git_branch,'build_number': build_number},**{'job_name': job_name})
    使用kwargs查找,找到,就更新,否则创建,更新或者创建的内容是:defaults的内容
    def update_or_create(self, defaults=None, **kwargs):
    """
    Look up an object with the given kwargs, updating one with defaults
    if it exists, otherwise create a new one.
    Return a tuple (object, created), where created is a boolean
    specifying whether an object was created.
    """
     

    filter总是返回一个对象集合,即使只有一个对象,get总是返回一个确定的对象,因此get是用来获取一个对象的
    查询所有:
    Rule.objects.all()
    过滤查询:get方法,使用相对简单,用法单一
    Rule.objects.get(id=222),对象不存在报错,对象多余一个也会报错
    Rule.objects.get(pk=222),对象不存在报错,pk=primary key主键
    filter方法
    Rule.objects.filter(id=222),对象不存在返回空的QuerySet:<QuerySet []>,等同于Rule.objects.filter(id__exact=222)
    Rule.objects.filter(plugin_name__iexact='Test')不区分大小写
    Rule.objects.filter(id=222).first()  返回单个对象,为空时返回None
    Rule.objects.filter(id=222).all()  返回所有对象,为空时返回<QuerySet []>
    级联查询:
    Rule.objects.all().filter(id=22)
    Rule.objects.all().filter(id=22).first()
    Rule.objects.all().filter(id=22).all()
    Rule.objects.all().filter(id=22).all().filter(id=22).get(id=22)
    模糊查询:格式,两个下划线字符后面跟的是筛选符号
    Rule.objects.filter(plugin_name__contains='test')
    Rule.objects.filter(plugin_name__contains='test').all()
    通过切片限制获取到的查询结果,切片可以节约内存,不支持负索引:
    Rule.objects.all()[:5]
    只获取某些列:
    Rule.objects.all().values('plugin_name','plugin_version')
    <QuerySet [{'plugin_name': 'ewo', 'plugin_version': ''}, {'plugin_name': 'ew2o', 'plugin_version': ''}, {'plugin_name': 'ew2o2', 'plugin_version': ''}]>
    
    Rule.objects.all().values_list('plugin_name','plugin_version')
    <QuerySet [('ewo', ''), ('ew2o', ''), ('ew2o2', '')]>
    
    排序查询:
    Rule.objects.order_by('plugin_name')
    取反:
    Rule.objects.order_by('-plugin_name')
    进一步过滤:
    Rule.objects.order_by('-plugin_name').filter(id=32)
    
    正则表达式:
    Person.objects.filter(name__regex="^abc")  # 正则表达式查询
    Person.objects.filter(name__iregex="^abc")  # 正则表达式不区分大小写
    
    Person.objects.exclude(name__contains="WZ")  # 排除包含 WZ 的Person对象
    Person.objects.filter(name__contains="abc").exclude(age=23)  # 找出名称含有abc, 但是排除年龄是23岁的

    去重:
    Rule.objects.filter(plugin_name__iexact='TesT').distinct()
    数量:
    Entry.objects.count()
    判断是否存在
    Entry.objects.all().exists()

    # 1. 使用 reverse() 解决
    Person.objects.all().reverse()[:2] # 最后两条
    Person.objects.all().reverse()[0] # 最后一条
     
    # 2. 使用 order_by,在栏目名(column name)前加一个负号
    Author.objects.order_by('-id')[:20] # id最大的20条


    QuerySet 是什么呢?


    从本质上说,QuerySet 是给定模型的对象列表(list)。QuerySet 允许您从数据库中读取数据,对其进行筛选以及排序。


    参考:

    https://code.ziqiangxuetang.com/django/django-queryset-api.html
    https://docs.djangoproject.com/en/2.1/topics/db/
    https://docs.djangoproject.com/zh-hans/2.1/topics/db/queries/#creating-objects

  • 相关阅读:
    XML-SAX
    aio-epoll
    aio-java
    设计模式-策略模式、命令模式
    java-io一
    计算机网络-tcp的可靠性
    计算机网络-tcp简介
    设计模式-单例模式、工厂模式
    Cookie和Session简述
    mysql-优化二
  • 原文地址:https://www.cnblogs.com/shengulong/p/10299833.html
Copyright © 2020-2023  润新知