1

Can I add additional fields to ModelSerializer subclass?

By saying 'additional field', I mean some fields don't belong any models in database, which any effort that try to map those fields to exist model fields will fail. The reason I need to include those fields is for design purpose. I need to those fields' value to do the validation and creating a new instance eventually.

I know there is a kwarg in ModelSerialzer called 'context'. By putting all the additional information into 'context', it will work. However, I want to know is that possible to create additional fields?

I have tried adding 'write_only=True', which doesn't work. The only left option is to override default restore_object method to create the instance with my will.

Any other ideas?

1 Answer 1

2

As you have not posted any code I can only give you a generic answer, but if I understand you correctly, you wish to add a custom field to a ModelSerializer thats not part of your model...

In DSF you can do this very esaily (read here):

In this case you just want a simple read-only field, so instead just use:

custom_field = Field(source='get_whatever')

In terms if validation after that please read the DRF guide here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.