Django 操作ORM
# App models 创建一张表
class Users(models.Model):
user_dat = models.DateTimeField(auto_now_add=True)
username = models.CharField(max_length=32)
pwd = models.CharField(max_length=64)
def orm_all(request): if request.method == 'GET': # 创建 # 创建第一方法 # orm_save = models.Users(username='xiaomo',pwd='123') # orm_save.save() # 创建数据,添加数据 第二种方法 # models.Users.objects.create(username='xiaoxiaomo',pwd='123456') # 字典添加 第三种方法 # dic_save = {"username":"Nike",'pwd':'123'} # models.Users.objects.create(**dic_save) # 查询 # user_all = models.Users.objects.all() # 查询所有 # print(user_all) # user_username_pwd = models.Users.objects.filter(username='xiaomo',pwd='123') # 根据条件查询 # for row in user_username_pwd: # print(row) # print(user_username_pwd) # 删除 # models.Users.objects.all().delete() # 删除所有 # models.Users.objects.filter(username='xiaomo').delete() # 指定删除 # 更新 # models.Users.objects.all().update(pwd='12345') # 修改所有的密码 # models.Users.objects.filter(pk=2).update(pwd='666') # 根据条件修改 # 获取个数 # print(models.Users.objects.filter(username='xiaomo').count()) # 执行原生sql # print(models.Users.objects.raw('select * from Users')) pass return HttpResponse('ok')
def orm_model_get(request): if request.method == 'GET': # 获取id 大于1 的值 gt # print(models.Users.objects.filter(pk__gt=1)) # 获取大于等于1的值 gte # print(models.Users.objects.filter(id__gte=1)) # 获取id 小于 5 的值 lt # print(models.Users.objects.filter(id__lt=5)) # 获取id 小于等于 5 的值 lte # print(models.Users.objects.filter(id__lte=5)) # 获取 id 大于1 且 小于 5 的值 in # print(models.Users.objects.filter(id__lt=5,id__gt=1)) # 获取id 为5, 1, 2, 的数据 # print(models.Users.objects.filter(id__in=[5,1,2])) # 排除 在这里面的都获取 not in exclude # print(models.Users.objects.exclude(id__in=[1,2])) # 查询为null的数据 # print(models.Users.objects.filter(username__isnull=True)) # contains 模糊匹配 # print(models.Users.objects.filter(username__contains='xi')) # icontains 不分大小写 # print(models.Users.objects.filter(username__icontains='Xiao')) # range 相当于 sql bettwen add # print(models.Users.objects.filter(pk__range=[1,2])) # order_by 排序 asc 升序排序,从小到大 # print(models.Users.objects.filter(username='xiaomo').order_by('id')) # -order_by 排序 desc 倒序, 从大到小 # print(models.Users.objects.filter(username='xiaomo').order_by('-id')) # limit 截取 # print(models.Users.objects.all()[:5]) # 截取5条数据 # day # print(models.Users.objects.filter(user_dat__day__gte=1)) # year # print(models.Users.objects.filter(user_dat__year=2020)) # month # print(models.Users.objects.filter(user_dat__month=7)) # week_day # print(models.Users.objects.filter(user_dat__week_day=4)) # hour # print(models.Users.objects.filter(user_dat__hour=15)) # minute 分钟 # print(models.Users.objects.filter(user_dat__minute=25)) # second 秒 # print(models.Users.objects.filter(user_dat__second=30)) pass return HttpResponse('ok')