Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using TastyPie to update a ForeignKey field to null

Is it possible to use TastyPie to update a ForeignKey field to None?

Related question: tastypie won't remove foreignkey reference during PUT

What I have:

class SomeObject(models.Model):
    some_field = models.ForeignKey(SomeOtherObject, null=True)

(and of course the corresponding TastyPie resource class that works fine for updating other fields)

What I want:

To update some_field to None using TastyPie.

What I've tried (in JavaScript):

$.put('/my/api/model/someobject/42/', { some_field: null });
$.put('/my/api/model/someobject/42/', { some_field: '/my/api/model/someotherobject/null/' });
$.put('/my/api/model/someobject/42/', { some_field: '' });
$.put('/my/api/model/someobject/42/', { some_field: 0 });
$.put('/my/api/model/someobject/42/', { some_field: false });

And so on. These all result in 404 or 400. Some result in 204, but the database is not updated.

Reading through the code in full_dehydrate(), it seems it might not be possible at present do so.

I've looked at the recent code on github, and I'm not convinced this is possible.

like image 497
djsmith Avatar asked Mar 14 '12 04:03

djsmith


1 Answers

Here is a generic solution. Create a base resource and extend all other resources from this one. It's a hack, but it works.

class MyResource(ModelResource):
    def obj_update(self, bundle, request=None, **kwargs):
        for field_name in self.fields:
            field = self.fields[field_name]

            if type(field) is ToOneField and field.null and bundle.data[field_name] is None:
                setattr(bundle.obj, field_name, None)

        return super(MyResource, self).obj_update(bundle, **kwargs)
like image 113
Adam Thomas Avatar answered Sep 22 '22 17:09

Adam Thomas