Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 784
Fraser Graham Avatar asked Apr 11 '13 15:04

Fraser Graham


2 Answers

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.

like image 57
Jarie Bolander Avatar answered Nov 09 '22 11:11

Jarie Bolander


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
like image 27
nickromano Avatar answered Nov 09 '22 11:11

nickromano