Django Serializer HiddenField隐藏字段实例
Django rest_framework serializer.HiddenField(default=serializer.CurrentUser())
在用Dajngo RestFramework时, 有时候需要这么一个场景,前端不需要传一个或多个字段,这些字是直接根据用户登录信息判断自动赋值的,如果用mixin和viewset进行搭配写接口,要么重写create, update等方法,要么就是在serializer_class时就定义默认值,而第二种方法明显简单一些。
具体看代码
# 假如我定义了一个serliazer,shop和status都是自动判断后赋值的 # 用HiddenField定义字段,default方法来写具体赋值函数 # default方法是一个类,需要重写set_context的方法 from rest_framework.compat import ( InvalidTimeError, MaxLengthValidator, MaxValueValidator, MinLengthValidator, MinValueValidator, unicode_repr, unicode_to_repr ) class CurrentShopDefault(object): def set_context(self, serializer_field): self.shop = serializer_field.context['request'].user.shop def __call__(self): return self.shop def __repr__(self): return unicode_to_repr('%s()' % self.__class__.__name__) class CurrentStatus(object): def set_context(self, serializer_field): user_info = serializer_field.context['request'].user if user_info.shop.shop_type == 'SHOP_TYPE_COMCIRCLE': self.status = 1 else: self.status = 2 def __call__(self): return self.status def __repr__(self): return unicode_to_repr('%s()' % self.__class__.__name__) # 定义serializer class GameSerializer(serializers.ModelSerializer): class Meta: model = Game exclude = ['created_time'] shop = serializers.HiddenField( default=CurrentShopDefault() ) status = serializers.HiddenField( default=CurrentStatus() )
最后在view文件的class里直接指定serializer_class就好了
class GameOpView(mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): """ retrieve: 获取-游戏详情 create: 创建-游戏 update: 更新-游戏 delete: 删除-游戏 partial_update: 更新游戏状态 total_info: 游戏数据总览 """ permission_classes = [IsShop, ] pagination_class = StandardResultsSetPagination def get_queryset(self): return Game.objects.filter( Q(shop=self.request.user.shop) | Q(shop__com_circle=self.request.user.shop)) def get_serializer_class(self): if self.action == 'partial_update': return GameStatusSerializer elif self.action == 'retrieve': return GameReadSerializer else: return GameSerializer
补充知识:drf 中serializers.HiddenField使用方法
class CurrentUser(object): def set_context(self, serializer_field): self.user_obj = serializer_field.context['request'].user def __call__(self): return self.user_obj class GetObjectFlow(object): def set_context(self, serializer_field): self.object_flow = serializer_field.context['request'].data.get('object_flow') # 这里需要在views中传进去呀,djangocontext上下文中才能取到 def __call__(self): return self.object_flow class AddHolidaySerializer(serializers.ModelSerializer, BaseModelSerializer): user = serializers.HiddenField(default=CurrentUser()) # 给用户外键赋当前请求的user object_flow = serializers.HiddenField(default=GetObjectFlow()) # 后端自己处理一些特殊的外键 status = serializers.HiddenField(default=0) # 默认新增时给status赋初值 class Meta: model = Holiday exclude = ('deleted',)
以上这篇Django Serializer HiddenField隐藏字段实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。
赞 (0)