有时候序列化的时候,有些字段不需要前端传给我,从后台就可以直接拿到,
比如user,直接就可以通过request.user获取,那么序列化的时候,我们可以通过重写save方法等其他方法,但是现在可以有一个更好的选择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')
当然你也可以重写
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__)
网友评论