zoukankan      html  css  js  c++  java
  • Django之model

    #插入一条数据:
    Blog.objects.create(title="The first blog of my site",content="I am writing my blog on Terminal")
    Blog.objects.all()
    #插入一条数据:
    Blog.objects.create(title=title,content=content)
    #避免重复可以用下面的格式:
    Blog.objects.get_or_create(title=title,content=content)
    #导出文件/导入文件,数据导入不需要知道APPname
    python manage.py dumpdata blog > blog_dump.json
    python manage.py loaddata blog_dump.json
    #批量导入数据,参数是一个列表,类似excutemany()
     Blog.objects.bulk_create(BlogList)
    #为这些修改创建迁移文件
    django不认识mysqlDB,安装pymysql替代,并在__init__.py中加上如下两句:
    import pymysql
    pymysql.install_as_MySQLdb()
    # django自带的迁移命令
    # 从原来的整个数据库导出所有数据
    python manage.py dumpdata > mysite_all_data.json
    # 将mysite_all_data.json传送到另一个服务器或电脑上导入
    python manage.py loaddata mysite_all_data.json
    # mysql本身的备份命令
    # mysql导出数据库 blog 到 blog.sql 文件中
    mysqldump -u username -p --database blog > blog.sql
    # mysql导入数据库到 新的服务器
    > source /path/to/blog.sql
    #创建超级管理员
    python manage.py createsuperuser
    
    
    #django自带查询:
    filter:过滤
    exclude:排除
    Person.objects.all()[5:15]:切片
    list=Person.objects.filter(name=name,age__lt=age)
    __gt:大于
    __lt:小于
    __gte:表示 大于或等于
    聚合运算
    Dict = AppPosts.objects.filter(date__gte=start_date,date__lte=end_date).values(date_format).annotate(posts=Avg('posts'),replies=Avg('replies'),likes=Avg('likes'),attentions=Avg('attentions'),votes=Avg('votes'))
    Person.objects.filter(name__contains="abc") # 名称中包含 "abc"的人
    Person.objects.filter(name__icontains="abc") #名称中包含 "abc",且abc不区分大小写
    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岁的
    Person.objects.filter(name__startswith='Paul')名字开头是paul
    Person.objects.count() :聚合函数计数
    Person.objects.order_by('date')[:10]:升序
    Person.objects.order_by('-date')[:10]:降序
    dict=AppKeyValue.objects.filter(dt__gte='2017-07-01',dt__lte='2017-07-05',c_key__in=['headline','community','car','service','my'])
    Django各种条件查询关键字:
    
    __exact 精确等于 like ‘aaa’ 
    __iexact 精确等于 忽略大小写 ilike ‘aaa’ 
    __contains 包含 like ‘%aaa%__icontains 包含 忽略大小写 ilike ‘%aaa%’,但是对于sqlite来说,contains的作用效果等同于icontains。 
    __gt 大于 
    __gte 大于等于 
    __lt 小于 
    __lte 小于等于 
    __in 存在于一个list范围内 
    __startswith 以…开头 
    __istartswith 以…开头 忽略大小写 
    __endswith 以…结尾 
    __iendswith 以…结尾,忽略大小写 
    __range 在…范围内 
    __year 日期字段的年份 
    __month 日期字段的月份 
    __day 日期字段的日 
    __isnull=True/False
    #更新数据
    test1 = Test.objects.get(id=1)
        test1.name = 'w3cschool菜鸟教程'
        test1.save()
    # 另外一种方式
    Test.objects.filter(id=1).update(name='w3cschool菜鸟教程')
    
    #修改所有的列
    Test.objects.all().update(name='w3cschool菜鸟教程')
    #删除数据
    test1 = Test.objects.get(id=1)
        test1.delete()
    # 另外一种方式
    Test.objects.filter(id=1).delete()
    # 删除所有数据
    Test.objects.all().delete()
    # django ORM增删改查
    from app01 import models  # 导入models模块
    def orm(request):
    # 创建数据
    # 第一种方式
    models.UserInfo.objects.create(username="root",password="123")
    # 第二种方式
    obj = models.UserInfo(username='fzh', password="iajtag")
    obj.save()
    # 第三种方式
    dic = {'username':'fgf', 'password':'666'}
    models.UserInfo.objects.create(**dic)
    
    # 查询数据
    result = models.UserInfo.objects.all()  # 查询所有,为QuerySet类型,可理解成列表
    result = models.UserInfo.objects.filter(username="fgf",password="666")  # 列表
    result = models.UserInfo.objects.filter(username="fgf").first()  # 对象
    条件查询。filter 相当于where查询条件,里面的","会组成and条件
    for row in result:  # 打印查询到数据。
        print(row.id,row.username,row.password)
    
    查看QuerySet类型具体做了什么事情,可以: print(result.query)
    
    # 删除数据
        models.UserInfo.objects.all().delete()  # 删除所有
        models.UserInfo.objects.filter(id=4).delete()  # 删除所有
    
    # 更新数据
        models.UserInfo.objects.all().update(password=8888)
        models.UserInfo.objects.filter(id=3).update(password=888888)
    
        
    # 获取单表数据的三种方式
    v1 = models.Business.objects.all() QuerySet类型 ,内部元素都是对象(对象内类似字典结构)
    [obj(id,caption,code), obj(id,caption,code), obj(id,caption,code)]
    v2 = models.Business.objects.all().values('id','caption') QuerySet ,内部元素都是字典,可以用list转化为列表
    [{'id':1,'caption':'运维'},{'id':1,'caption':'运维'},{'id':1,'caption':'运维'}]
    v3 = models.Business.objects.all().values_list('id','caption') QuerySet ,内部元素都是元组
    [(1,运维),(2,开发)]
    obj = Business.objects.get(id=1) 获取到的一个对象,如果不存在就报错DoesNotExist
    obj = Business.objects.filter(id=1).first() 对象或者None
    
    # 获取个数
    models.Tb1.objects.filter(name='seven').count()
    # 大于,小于
    models.Tb1.objects.filter(id__gt=1)      # 获取id大于1的值
    models.Tb1.objects.filter(id__gte=1)      # 获取id大于等于1的值
    models.Tb1.objects.filter(id__lt=10)     # 获取id小于10的值
    models.Tb1.objects.filter(id__lte=10)     # 获取id小于10的值
    models.Tb1.objects.filter(id__lt=10, id__gt=1)   # 获取id大于1 且 小于10的值
    # in
    models.Tb1.objects.filter(id__in=[11, 22, 33])   # 获取id等于11、22、33的数据
    models.Tb1.objects.exclude(id__in=[11, 22, 33])  # not in
    # isnull
    Entry.objects.filter(pub_date__isnull=True)
    # contains
    models.Tb1.objects.filter(name__contains="ven")
    models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感
    models.Tb1.objects.exclude(name__icontains="ven")
    # range
    models.Tb1.objects.filter(id__range=[1, 2])   # 范围bettwen and
    # 其他类似
    startswith,istartswith, endswith, iendswith,
    # order by
    models.Tb1.objects.filter(name='seven').order_by('id')    # asc
    models.Tb1.objects.filter(name='seven').order_by('-id')   # desc
    # group by
    from django.db.models import Count, Min, Max, Sum
    models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))
    SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"
    
    # limit 、offset
    # Python中的切片也可以用在模型的查询结果中:
    models.Tb1.objects.all()[10:20]
    
    # regex正则匹配,iregex 不区分大小写
    Entry.objects.get(title__regex=r'^(An?|The) +')
    Entry.objects.get(title__iregex=r'^(an?|the) +')
    # date
    Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
    Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))
    # year
    Entry.objects.filter(pub_date__year=2005)
    Entry.objects.filter(pub_date__year__gte=2005)
    # month
    Entry.objects.filter(pub_date__month=12)
    Entry.objects.filter(pub_date__month__gte=6)
    # day
    Entry.objects.filter(pub_date__day=3)
    Entry.objects.filter(pub_date__day__gte=3)
    # week_day
    Entry.objects.filter(pub_date__week_day=2)
    Entry.objects.filter(pub_date__week_day__gte=2)
    # hour
    Event.objects.filter(timestamp__hour=23)
    Event.objects.filter(time__hour=5)
    Event.objects.filter(timestamp__hour__gte=12)
    # minute
    Event.objects.filter(timestamp__minute=29)
    Event.objects.filter(time__minute=46)
    Event.objects.filter(timestamp__minute__gte=29)
    # second
    Event.objects.filter(timestamp__second=31)
    Event.objects.filter(time__second=2)
    Event.objects.filter(timestamp__second__gte=31)
  • 相关阅读:
    leetcode 2 Add Two Numbers
    log4j2 springboot 特点与使用方法
    数据类型和运算符
    初识Java
    《梦断代码》阅读笔记02
    《梦断代码》阅读笔记01
    场景调研
    【站立会议】第九天
    【站立会议】第八天
    【站立会议】第七天
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/6529993.html
Copyright © 2011-2022 走看看