您好,登录后才能下订单哦!
小编给大家分享一下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隐藏字段的示例分析”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。