0

一大波Model操作

 2 years ago
source link: https://dyl521.github.io/pages/987539/#_03-%E6%97%B6%E9%97%B4%E8%BF%87%E6%BB%A4
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

# 01.基本操作

from django.shortcuts import HttpResponse
from app01 import models

def orm(request):
    # 1 创建
    # 创建数据方法一
    models.UserInfo.objects.create(username='root', password='123')
    # 创建数据方法二
    obj = models.UserInfo(username='alex', password='123')
    obj.save()
    # 创建数据库方法三(传入字典必须在字典前加两个星号)
    dic = {'username': 'eric', 'password': '666'}
    models.UserInfo.objects.create(**dic)

    # 2 查
    result = models.UserInfo.objects.all()  # 查找所有条目
    result = models.UserInfo.objects.filter(username='alex', password='123')
    for row in result:
        print(row.id, row.username, row.password)

    # 3 删除
    models.UserInfo.objects.all().delete()  # 删除所有
    models.UserInfo.objects.filter(username='alex').delete()  # 删除指定

    # 4 更新
    models.UserInfo.objects.all().update(password='12345')
    models.UserInfo.objects.filter(id=4).update(password='15')

    # 5 获取个数
    models.UserInfo.objects.filter(name='seven').count()

    # 6 执行原生SQL
    # 6.1 执行原生SQL
    models.UserInfo.objects.raw('select * from userinfo')

    # 6.2 如果SQL是其他表时,必须将名字设置为当前UserInfo对象的主键列名
    models.UserInfo.objects.raw('select id as nid from 其他表')

    # 6.3 指定数据库
    models.UserInfo.objects.raw('select * from userinfo', using="default")

    return HttpResponse('orm')

# 02.进阶操作

  • 进阶操作:牛掰掰的双下划线
1、大于,小于
        # 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的值
2、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
3、isnull
        # Entry.objects.filter(pub_date__isnull=True)         #双下划线isnull,查找pub_date是null的数据
4、contains                                                    #就是原生sql的like操作:模糊匹配
        # models.Tb1.objects.filter(name__contains="ven")
        # models.Tb1.objects.filter(name__icontains="ven")    # icontains大小写不敏感
        # models.Tb1.objects.exclude(name__icontains="ven")
5、range
        # models.Tb1.objects.filter(id__range=[1, 2])          # 范围bettwen and
6、order by
        # models.Tb1.objects.filter(name='seven').order_by('id')      # asc     没有减号升续排列
        # models.Tb1.objects.filter(name='seven').order_by('-id')     # desc      有减号升续排列
7、group by
        # from django.db.models import Count, Min, Max, Sum
        # models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))        #根据id列进行分组
        # SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" 
        # WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"
8、limit 、offset    #分页
        # models.Tb1.objects.all()[10:20]
9、regex正则匹配,iregex 不区分大小写
        # Entry.objects.get(title__regex=r'^(An?|The) +')
        # Entry.objects.get(title__iregex=r'^(an?|the) +')

      
10、date
        # Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))          #__data表示日期查找,2005-01-01
        # Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))
11、year
        # Entry.objects.filter(pub_date__year=2005)                               #__year根据年查找
        # Entry.objects.filter(pub_date__year__gte=2005)
12、month
        # Entry.objects.filter(pub_date__month=12)
        # Entry.objects.filter(pub_date__month__gte=6)
13、day
        # Entry.objects.filter(pub_date__day=3)
        # Entry.objects.filter(pub_date__day__gte=3)
14、week_day
        # Entry.objects.filter(pub_date__week_day=2)
        # Entry.objects.filter(pub_date__week_day__gte=2)
15、hour
        # Event.objects.filter(timestamp__hour=23)
        # Event.objects.filter(time__hour=5)
        # Event.objects.filter(timestamp__hour__gte=12)
16、minute
        # Event.objects.filter(timestamp__minute=29)
        # Event.objects.filter(time__minute=46)
        # Event.objects.filter(timestamp__minute__gte=29)
17、second
        # Event.objects.filter(timestamp__second=31)
        # Event.objects.filter(time__second=2)
        # Event.objects.filter(timestamp__second__gte=31)

# 03.时间过滤

  • 根据天/小时进行过滤
from django.utils import timezone
from report.models import *

now = timezone.now()
# start_time = now - timezone.timedelta(days=7)
start_time = now - timezone.timedelta(hours=240)  # 查询10天前的数据
end_time = now

qs = AllClarm.objects.filter(start_tm__range=(start_time, end_time))

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK