您好,登錄后才能下訂單哦!
小編給大家分享一下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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。