To override the returned representation, you can override the `to_representation` method of a serializer:
def to_representation(self, instance): data = super().to_representation(instance) data.pop('secret_field') data['some_new_field'] = 'Cow infiltrator!' data['nested_data'] = {'fav_toys': ['pogo_stick', 'cannon balls']} return data Nested serializers are handled as per the docs: https://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization You can specify arbitary fields in your serializer with https://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly Or use a callable via a method field: https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield You don't live in South Africa by any chance? Cheers! On Thursday, 29 December 2022 at 23:55:04 UTC+2 Travis Miller wrote: > I'm new to DRF (and pretty new to Django and Python in general). I'm > trying to build a simple API endpoint. But I'm having trouble figuring out > the best approach. > > 1. The endpoint accepts a request payload similar to the following (this > is contrived): > > { > "employee_id": 123, > "favorite_flavor": "chocolate", > "subscribe_to_updates": true, > "cats_or_dogs": "cats" > } > > Obviously, I would like to validate this payload before doing anything > further with it. > > 2. The endpoint then creates several related records in the database. Note > that the request payload is *not* a direct 1-to-1 representation of a > Django ORM model. Instead, employee_id gets saved to one table, and > favorite_flavor and subscribe_to_updates get saved to a second table. > Perhaps cats_or_dogs doesn't get saved to the database at all – maybe it > just triggers an email send, or writes a file to disk, or something like > that. > > 3. Finally, I would like the endpoint to return an arbitrary JSON payload, > which differs from both the request payload *and* the model structure: > > { > "recommended_dessert": "Black Forest Cake", > "subscription_id": 5827, > "cat_name": "Fluffy", > "some_nested_object": { > "foo": "bar" > } > } > > How can I do this? DRF provides a dizzying array of ways to do things, and > I can't quite figure out which combination is best for my case. > > Thanks! > > -- You received this message because you are subscribed to the Google Groups "Django REST framework" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-rest-framework/bfabc8ef-47b8-402c-b1bc-2b072753e9c9n%40googlegroups.com.