简体   繁体   中英

Django Rest Framework - serializer fields for only deserialization

I am writing a simple API for encrypting/decrypting ciphertexts using Django Rest Framework, and I was wondering if it is possible for me to define fiends in a serializer that are only for deserialization (ie only for validation). For example, I have a model class called Message , and I have a view that allows users to create Message objects. When I call serializer.is_valid() , I would like to check that a field called plaintext is not empty/null, but when I display a Message to the user I would like to make the plaintext field into a HyperlinkedIdentityField instead of directly showing it. In other words, I want users to be able to post a message like this:

{ 
  "plaintext": "blah",
  "key": "tunafish"
}

and then, after validating it, I would show the user something like:

{
  "plaintext": "link/to/plaintext",
  "ciphertext": "link/to/ciphertext",
  "key": "tunafish"
}

Is it possible to do this with only one serializer?

Django Rest Framework serializers have two functions that you can override to have custom (different) behavior for incoming and outgoing fields: to_internal_value (from a dict) and to_representation (from your django model instance).

In your case I would make the field a HyperlinkedIdentityField and do whatever work you need to in to_internal_value to create the relationship between your instance and the plaintext instance.

See this documentation on creating a custom field api - http://www.django-rest-framework.org/topics/3.0-announcement/#changes-to-the-custom-field-api

Or read the source here - https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM