有時(shí)候序列化的時(shí)候,有些字段不需要前端傳給我,從后臺(tái)就可以直接拿到,
比如user,直接就可以通過request.user獲取,那么序列化的時(shí)候,我們可以通過重寫save方法等其他方法,但是現(xiàn)在可以有一個(gè)更好的選擇HiddenField
#源碼
class CurrentUserDefault(object):
def set_context(self, serializer_field):
self.user = serializer_field.context['request'].user
def __call__(self):
return self.user
def __repr__(self):
return unicode_to_repr('%s()' % self.__class__.__name__)
添加user代碼序列化中
class PyUserProfileUpdateSeriazerFE(serializers.ModelSerializer):
follow_project = serializers.ListField(allow_empty=True)
user = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = UserProfile
fields = ('user', 'city', 'follow_project')
當(dāng)然你也可以重寫
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__)