动态地包含或排除Serializer类字段 [英] Dynamically include or exclude Serializer class fields
问题描述
在我的用户
个人资料模型中,我已经包含了一个 show_email
字段。因此,要将此功能添加到我的API中,UserSerializer类如下所示:
class UserSerializer (serializer.ModelSerializer):
email = serializers.SerializerMethodField('show_email')
def show_email(self,user):
return user.email if user.show_email else None
class Meta:
model = django.contrib.auth.get_user_model()
fields =(username,first_name,last_name,email)
但我真的不喜欢它。我认为如果字段电子邮件
将完全排除在序列化程序输出之外,那将是一个很好的清单 show_email
是 False
,而是显示丑陋的email:null
东西。
您可以通过覆盖返回响应的方法在您的API视图中执行此操作,即API视图的动词。例如,在ListAPIView中,您将覆盖 get()
:
class UserList(generics.ListAPIView):
model = django.contrib.auth.get_user_model()
serializer_class = UserSerializer
def get(self,request,* args,** kwargs)
response = super(UserList,self).get(request,* args,** kwargs)
用于response.data ['results']:
if result [ 'email']为无:
result.pop('email')
返回响应
你可能想添加一些更多的属性检查,但这是如何做到这一点的要点。另外,我补充说,如果期望它们存在于所有记录中,则从某些结果中删除字段可能会导致消费应用程序出现问题。
In my User
profile model I've included a show_email
field explicitly. So, to add this feature to my API, the UserSerializer class looks like this:
class UserSerializer(serializers.ModelSerializer):
email = serializers.SerializerMethodField('show_email')
def show_email(self, user):
return user.email if user.show_email else None
class Meta:
model = django.contrib.auth.get_user_model()
fields = ("username", "first_name", "last_name", "email")
But I don't really like it. I think it would be a lot cleaner if the field email
would be completely excluded from the serializer output it show_email
is False
, instead showing that ugly "email": null
thing.
How could I do that?
You could do this in your API view by overriding the method returning the response, i.e. the "verb" of the API view. For example, in a ListAPIView you would override get()
:
class UserList(generics.ListAPIView):
model = django.contrib.auth.get_user_model()
serializer_class = UserSerializer
def get(self, request, *args, **kwargs):
response = super(UserList, self).get(request, *args, **kwargs)
for result in response.data['results']:
if result['email'] is None:
result.pop('email')
return response
You would probably want to add some more checking for attributes, but that's the gist of how it could be done. Also, I would add that removing fields from some results may cause issues for the consuming application if it expects them to be present for all records.
这篇关于动态地包含或排除Serializer类字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!