django ORM 序列化 操作
作者:互联网
ORM
''' filter示例使用 ''' ''' res = Xyuser.objects.filter(id=request.data.get('id'), role_id__in=(2, 5)).update(is_active=0) instance = Xyuser.objects.filter(id=request.data.get('id')).first() # 取修改后数据instance users = Xyuser.objects.all().filter(is_active=1, role_id__in=(2, 3, 4, 5)).order_by( '-create_time') total = users.count()
user = Xyuer.lobjects.get(id=1)
''' ''' create使用示例 ''' ''' BookInfo.objects.create(name="Python教程",readcount=0,commentcount=0) book = BookInfo(name="Django教程",readcount=0,commentcount=0) # 创建BookInfo对象 book.save() # 使用save方法保存到数据库 ''' ''' update使用示例 ''' ''' User.objects.filter(id=1).update(role=2) User.objects.filter(id=1).update(**{'username': 'nick', 'role': 3}) _role = Role.objects.get(id=2) User.objects.filter(id=1).update(role=_role) _role = Role.objects.get(id=1) User.objects.filter(id=1).update(**{'username': 'nick', 'role': _role}) _t = User.objects.get(id=1) _t.__dict__.update(**{'username': 'nick', 'role_id': 2}) _t.save() _t = User.objects.get(id=1) _t.usernam e ='nick' _t.is_activ e =True _t.save() ''' ''' update_or_create使用示例 这个规则是: update_or_create(defaults=None, **kwargs) 执行规则: filter kwargs,create/update defaults 返回值为元组: (object, created),object为新建或者更新的对象,created为一个布尔值,表示是新建还是更新,True为新建 ''' ''' Model.objects.update_or_create(defaults ,**kwargs) Draw2DDevice.objects.update_or_create( defaults={'x': 777, 'y': 777, }, device_id=13, version_id=1) obj, create =models.CommodityInventory.objects.update_or_create( inventory_id=key["inventory_id"], defaults={ "colour": key["colour"], # 规格名称 "bazaar": key["bazaar"], # 市场价 "price": key["price"], # 价格 "number": key["number"], # 库存 } ) defaults = dict() defaults['name'] = 'Jeff' defaults['idcard'] = '123456' defaults['content'] = 'hello world' User.objects.update_or_create(defaults=defaults, name='Jeff', idcard='123456') '''
序列"""
GET /books/ 提供所有记录 POST /books/ 新增一条记录 GET /books/<pk>/ 提供指定id的记录 PUT /books/<pk>/ 修改指定id的记录 DELETE /books/<pk>/ 删除指定id的记录 一、定义 APIView 序列化器 class BookInfoModelSerializer(serializers.ModelSerializer): class Meta: model = BookInfo fields = '__all__'
# []
# exclude =
# read_only_fields = []
二、View 视图中使用 1、查询全部数据 (GET /books/ 提供所有记录) def get(self, request): qs = BookInfo.objects.all() # 展示数据用instance属性 serializer = BookInfoModelSerializer(instance=qs, many=True) print(serializer.data) return Response(serializer.data) 2、新增数据 (POST /books/ 新增一条记录) def post(self, request): # 获取前端传入的请求体数据 data = request.data # 创建序列化器进行反序列化 serializer = BookInfoModelSerializer(data=data) # 调用序列化器的is_valid方法进行校验 serializer.is_valid(raise_exception=True) # 调用序列化器的save方法进行执行create方法 serializer.save() # 响应 return Response(serializer.data, status=status.HTTP_201_CREATED) 3、根据pk查询一条数据 (GET /books/<pk>/ 提供指定id的记录) def get(self, request, pk): # 查询pk指定的模型对象 try: book = BookInfo.objects.get(id=pk) except BookInfo.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) # 创建序列化器进行序列化 serializer = BookInfoModelSerializer(instance=book) # 响应 return Response(serializer.data) 4、根据pk进行修改一条数据 (PUT /books/<pk>/ 修改指定id的记录) def put(self, request, pk): # 查询pk所指定的模型对象 try: book = BookInfo.objects.get(id=pk) except BookInfo.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) # 获取前端传入的请求体数据 # 创建序列化器进行反序列化 serializer = BookInfoModelSerializer(instance=book, data=request.data) # 校验 serializer.is_valid(raise_exception=True) # save--->update serializer.save() # 响应 return Response(serializer.data) 5、删除一条数据 (DELETE /books/<pk>/ 删除指定id的记录) def delete(self, request, pk): # 查询pk所指定的模型对象 try: book = BookInfo.objects.get(id=pk) except BookInfo.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) book.delete() return Response(status=status.HTTP_204_NO_CONTENT) """
标签:objects,get,update,django,ORM,序列化,data,id,serializer 来源: https://www.cnblogs.com/pearlcity/p/16548540.html