Created
February 14, 2018 18:06
-
-
Save michaelhelmick/8fa8a69502715adfa85e2a8e20550d47 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SerializerMethodKwargField(serializers.SerializerMethodField): | |
def __init__(self, *args, **kwargs): | |
default_args = [ | |
'read_only', 'write_only', 'required', 'default', 'initial', 'source', 'label', | |
'help_text', 'style', 'error_messages', 'validators', 'allow_null'] | |
kwargs_to_del = [] | |
self.method_kwargs = {} | |
for kwarg in kwargs: | |
if kwarg not in default_args: | |
if kwarg == 'method': | |
self.method = kwargs[kwarg] | |
else: | |
self.method_kwargs.update({ | |
kwarg: kwargs[kwarg], | |
}) | |
kwargs_to_del.append(kwarg) | |
for kwarg in kwargs_to_del: | |
del kwargs[kwarg] | |
super(SerializerMethodKwargField, self).__init__(*args, **kwargs) | |
def to_representation(self, obj): | |
return getattr(obj, self.method)(**self.method_kwargs) | |
class MyModelSerializer(serializers.ModelSerializer): | |
avatar = SerializerMethodKwargField(source='*', method='get_avatar') | |
avatar_sm = SerializerMethodKwargField(source='*', method='get_avatar', size='small') | |
class Meta: | |
model = MyModel | |
fields = ('avatar', 'avatar_sm',) | |
class MyModel(models.Model): | |
avatar = models.ImageField(...) | |
def get_avatar(self, size='default'): | |
if size == 'small': | |
return 'small image' | |
return 'original image' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BooleanKwargField(serializers.BooleanField): | |
def __init__(self, *args, **kwargs): | |
default_args = [ | |
'read_only', 'write_only', 'required', 'default', 'initial', 'source', 'label', | |
'help_text', 'style', 'error_messages', 'validators', 'allow_null'] | |
kwargs_to_del = [] | |
self.method_kwargs = {} | |
for kwarg in kwargs: | |
if kwarg not in default_args: | |
if kwarg == 'method': | |
self.method = kwargs[kwarg] | |
else: | |
self.method_kwargs.update({ | |
kwarg: kwargs[kwarg], | |
}) | |
kwargs_to_del.append(kwarg) | |
for kwarg in kwargs_to_del: | |
del kwargs[kwarg] | |
super(SerializerMethodKwargField, self).__init__(*args, **kwargs) | |
def to_representation(self, obj): | |
return getattr(obj, self.method)(**self.method_kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment