Regardless of whether this is good or not, there are times when you want to access View information from Serializer. We use a convenient Mixin that can be used in such cases internally. The more you do, the stronger the bond between View and Serializer, so we recommend that you follow the usage and dosage __.
Anyway, it's the source code.
ViewAccessSerializerMixin
class ViewAccessSerializerMixin(object):
def get_view_action(self):
"""
Access View action from Serializer
"""
context = getattr(self, 'context')
if not context:
warnings.warn('The context does not exist in the serializer. The instance is created in an illegal way')
return None
return context.get('view').action
def get_view_kw(self, key, default=None):
"""
Access view kwargs from Serializer
"""
context = getattr(self, 'context')
if not context:
warnings.warn('The context does not exist in the serializer. The instance is created in an illegal way')
return default
return context.get('view').kwargs.get(key, default)
def get_kwargs_object(self, key, model_class):
"""
Access kwargs from the Serializer, treat it as an id, and search for the specified model
"""
obj = model_class.objects.get_or_none(id=int(self.get_view_kw(key, 0)))
if obj:
return obj
Mostly used in validation
. I think there are probably better conditions. Like this.
class HogeSerializer(ViewAccessSerializerMixin, serializers.ModelSerializer):
#Various omissions
def validate(self, attrs):
#Change the verification content depending on the action
action_name = self.get_view_action()
if action_name == "xxxx":
pass
else:
pass
Mostly used in SerializerMethodField.
class PostHistorySerializer(ViewAccessSerializerMixin, serializers.ModelSerializer):
#Various omissions
comments = serializers.SerializerMethodField()
def get_comments(self, obj):
return obj.comment.filter(user_id=self.get_view_kw("user_pk"))
It's close to the combination of ↑, but it's a shortcut.
class UserSerializer(ViewAccessSerializerMixin, serializers.ModelSerializer):
#Various omissions
def validate(self, attrs):
user = self.get_kwargs_object('user_pk', models.User)
if user.is_ban():
raise NotFound()
pass
Basically, I use it like this. I hope you can use it conveniently.
Recommended Posts