queryset = User.objects.all() # 查询所有数据 queryset = User.objects.get(home='郑州') # 查询一条数据 queryset = User.objects.filter(home='郑州').count() # 查询结果的数量 queryset = User.objects.exclude(home='郑州') # 查询结果取反
queryset = User.objects.filter(home__contains='南') # 查询结果包含’南‘
- startswith,endswith 以指定的值开头或结尾
queryset = User.objects.filter(home__startswith='平') # 查询结果以’平‘开头 queryset = User.objects.filter(home__endswith='州') # 查询结果以’州‘结尾
queryset = User.objects.filter(home__isnull=False) # 查询结果 true为空 false不为空
queryset = User.objects.filter(id__in=[3,5]) # 查询id 3 或 5
- range 相当于between...and...
queryset = User.objects.filter(id__range=[3,5]) # 查询id 3 - 5(范围)
-
-
gte 大于等于
-
lt 小于
-
lte 小于等于
-
queryset = User.objects.filter(id__gt=4) # 查询id大于4 queryset = User.objects.filter(id__gte=4) # 查询id大于等于4 queryset = User.objects.filter(id__lt=4) # 查询id小于4 queryset = User.objects.filter(id__lte=4) # 查询id小于等于4 queryset = User.objects.exclude(id=4) # 查询id不等于4
queryset = User.objects.filter(Q(id=5) | Q(age=42)) # 查询id等于5 或 age等于42 queryset = User.objects.filter(Q(id=5) & Q(age=18)) # 查询id等于5 与 age等于42
queryset = User.objects.aggregate(sum('age')) # 年龄求和
queryset = User.objects.all().order_by('-hight') # 身高降序 queryset = User.objects.all().order_by('hight') # 年龄升序
def post(self,res): r_name = res.data.get('r_name') u_name = res.data.get('u_name') if not all([r_name,u_name]): return Response({'code':400,'msg':'参数不完整'}) # # 正向操作 # user_obj = User.objects.get(username=u_name) # role_obj = Role.objects.get(role_name=r_name) # user_obj.roles.add(role_obj) # 反向操作 role_obj=Role.objects.get(role_name=r_name) user_obj=User.objects.filter(username=u_name) role_obj.user_set.add(*user_obj) return Response({'code':200,'data':'添加成功'})
def get(self,res): # 获取 r_id = res.query_params.get('r_id') u_id = res.query_params.get('u_id') # 验证 if not all([r_id,u_id]): return Response({'code':400,'msg':'参数不完整'}) # 逻辑与入库 # # 正向操作 # user_obj=User.objects.get(id=u_id) # role_obj=user_obj.roles.all() # ser_obj=RoleSer(role_obj,many=True) # 反向操作 role_obj=Role.objects.get(id=r_id) user_obj=role_obj.user_set.all() ser_obj=UserSer(user_obj,many=True) # 返回 data = ser_obj.data return Response({'code':200,'data':data})
def put(self,res): r_id = res.data.get('r_id') u_id = res.data.get('u_id') if not all([r_id,u_id]): return Response({'code':400,'msg':'参数不完整'}) user_obj = User.objects.filter(id=u_id).first() role_obj = Role.objects.filter(id=r_id) user_obj.roles.set(role_obj) return Response({'code':200,'data':'修改成功'})
def delete(self,res): r_id = res.GET.get('r_id') u_id = res.GET.get('u_id') if not all([r_id, u_id]): return Response({'code':400,'msg':'参数不完整'}) user_obj=User.objects.filter(id=u_id).first() role_obj=Role.objects.filter(id=r_id).first() user_obj.roles.remove(role_obj) return Response({'code':200,'data':'删除成功'})