Search code examples
pythondjangoresttastypie

Tastypie get_or_create object


Is it possible to create a default object in tastypie? I'd like to create an object the first time it's retrieved through the REST api, so there's always a returned value. I could do this in dehydrate, but I also need to take into account GET parameters to create the object. What would be the best method to overload and how can I related objects (which the GET parameter refers to)?


Solution

  • I may have found 'a' solution.

    In ModelResource, I overload obj_get_list:

    def obj_get_list(self, bundle, **kwargs):
        if bundle.request.method == 'GET':
            related_id = bundle.request.GET['entity']
            # create new object if it doesn't exist and populate with `related_id`
            # ...
        objects = ModelResource.obj_get_list(self, bundle, **kwargs)
        return objects
    

    The url to call this would have a GET parameter /url/to/resource?entity=1.

    Is there anything wrong with this solution? Can anyone foresee undesired side effects?