Django TastyPie, how to trigger action after POST with ManyToMany fields?
Asked Answered
P

2

5

I have a REST API built using Django and TastyPie. My goal is to add a task to my job queue when new data is POSTed to a particular model.

I was going to hook into post_save and trigger then but the model contains ManyToMany relationships and so the post_save is triggered before the m2m relationships update and hooking into the m2m_changed signal seems messy. I get multiple signal events and my code will need to check the instance after each one and try and determine if it's ready to trigger the event. Some of the ManyToMany fields can be Null so when I get an m2m_changed signal I don't really know for sure if it's done saving.

Is there a correct way to do this? Does TastyPie allow me to hook into the POST event and do something at the end? All the things I have found point me at post_save events to do this.

Does Django have a way to signal me when all m2m updates for a given model instance are completed?

Pieter answered 11/4, 2013 at 15:57 Comment(2)
I found a slighly less unpleasant way to do this by overriding the tastypie create_response() method that gets called after all the models are saved. I still don't like it.Pieter
I also attempted to use wrap_view, but that requires me to re-parse the content of the response to get the ID of the object just created. Seems very inefficient.Pieter
H
8

If you are using POST, then obj_update() does not appear to work for me. What did work was using obj_create() as follows:

class Resource(ModelResource):
    def obj_create(self,bundle,**kwargs):
        bundle = super(Resource,self).obj_create(bundle,**kwargs)

        # Add code here

        return bundle

One thing to note is that request is not included. I tried that and it gave me an error.

Harbison answered 24/5, 2013 at 22:30 Comment(1)
You can get to the request from inside the bundle. bundle.request is working fine for me.Pieter
G
6

You should be able to override the obj_update method

class Resource(ModelResource):
    def obj_update(self, bundle, request, **kwargs):
        bundle = super(Resource, self).obj_update(bundle, **kwargs)

        # queue your task here
        return bundle
Genniegennifer answered 12/4, 2013 at 6:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.