Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add a Writeable SerializerMethodField to DRF#8216

Unanswered
HHHMHA asked this question inIdeas & Suggestions
Discussion options

You know how the front end guys always want the format output in a weird way right?

including a field where we can format the outputs will be great, there are solutions online like this:

classWriteableSerializerMethodField(serializers.Field):def__init__(self,write_serializer=None,method_name=None,**kwargs):assertwrite_serializerisnotNoneandisinstance(write_serializer,serializers.Field),'write_serializer must be a valid serializer field'self.write_serializer=write_serializerself.method_name=method_namesuper(WriteableSerializerMethodField,self).__init__(**kwargs)defbind(self,field_name,parent):# In order to enforce a consistent style, we error if a redundant# 'method_name' argument has been used. For example:# my_field = serializer.CharField(source='my_field')default_method_name='get_{field_name}'.format(field_name=field_name)assertself.method_name!=default_method_name, ("It is redundant to specify `%s` on SerializerMethodField '%s' in ""serializer '%s', because it is the same as the default method name. ""Remove the `method_name` argument."%            (self.method_name,field_name,parent.__class__.__name__)        )# The method name should default to `get_{field_name}`.ifself.method_nameisNone:self.method_name=default_method_namesuper(WriteableSerializerMethodField,self).bind(field_name,parent)defto_internal_value(self,data):returnself.write_serializer.to_internal_value(data)defto_representation(self,value):method=getattr(self.parent,self.method_name)returnmethod(value)

just wondering if it can be added to DRF.

You must be logged in to vote

Replies: 3 comments 3 replies

Comment options

can you share the output format/formats please to understand the reasoning behind it?

You must be logged in to vote
3 replies
@HHHMHA
Comment options

Let's assume we have a phone field
it will come as input like this: +963XXXXXXXXXX
But front end want the output like this:

    "phone": {        "prefix": "+963",        "number": "XXXXXXXXXX",        "flag": "",    }

If we have the field above we can use something like this:

phone = WriteableSerializerMethodField(    write_serializer=serializers.CharField(<params_here>) # Or use the PhoneField whatever)def get_phone(self, phone):    return {        "prefix": <code_for_prefix>,        "number": <code_for_number>,        "flag": <code_for_flag    }
@auvipy
Comment options

i think you can do this in model level as well or them using a model method and make the output in API as well

@HHHMHA
Comment options

There are multiple ways to solve this yes, we can in the view for example replace the data["phone"]
but in the serializer like this would be the best

Comment options

This is a great idea. My desired usage for such aReadWriteSerializerMethodField would look like this:

fromdjango.contrib.auth.modelsimportUserfromdjango.utils.timezoneimportnowfromrest_frameworkimportserializersclassUserSerializer(serializers.ModelSerializer):days_since_joined=serializers.ReadWriteSerializerMethodField()classMeta:model=Userfields='__all__'defget_days_since_joined(self,obj):return (now()-obj.date_joined).daysdefset_days_since_joined(self,instance:User,value:int):instance.date_joined=now()-time_in_days(value)

In the setter I can directly interact with instance of my object.

You must be logged in to vote
0 replies
Comment options

While theSerializerMethodField is a quick shortcut for read-only fields, if you need read + write, then I think you're better off writing a separate serializer, handling read and write in a self-contained way.

The OP seems to imply the need forwrite_serializer anyway, so this would need to be written.

Thesecond example with a getter and setter methods might be a better API, but I can see that becoming very messy as the number of fields grow.

Overall, I'm -1 on this 👎🏻

You must be logged in to vote
0 replies
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Labels
None yet
4 participants
@HHHMHA@browniebroke@auvipy@pktiuk

[8]ページ先頭

©2009-2025 Movatter.jp