Search code examples
pythondjangotastypie

Returning non-predefined fields via. API with Tastypie in Django


I am using Tastypie for non-ORM data source (Amazon Dynamodb). I have gone through the official documentation for non-ORM source and found the following code:

class MessageResource(Resource):
    # Just like a Django ``Form`` or ``Model``, we're defining all the
    # fields we're going to handle with the API here.
    uuid = fields.CharField(attribute='uuid')
    user_uuid = fields.CharField(attribute='user_uuid')
    message = fields.CharField(attribute='message')
    created = fields.IntegerField(attribute='created')

I am new to Tastypie and what I understand is that fields uuid, message, created.. which are returned by API are defined over here. Is there any way that I return those fields that are not defined here i.e. all those fields returned by the dictionary in obj_get_list or obj_get.


Solution

  • You can use the dehydrade method. Simply add a new key to bundle.data.

    def dehydrate(self, bundle):
        for item in bundle.obj.iteritems():
            bundle.data["new_key"] = "new_value"
        return bundle