Search code examples
djangotastypie

Tastypie foreign key set null


I need to set foreign key to null while updating the object.

Here is the model:

class Task(models.Model):
    parent_milestone = models.ForeignKey("Milestone", null=True, blank=True)
    parent_task = models.ForeignKey("Task", null=True, blank=True)

    name = models.CharField(max_length=256)
    description = models.TextField(blank=True, null=True)
    deadline = models.DateTimeField(blank=True, null=True)
    priority = models.IntegerField(default=2)

    done = models.BooleanField(default=False)

    def __unicode__ (self):
        return self.name

Here is the tastypie resource:

class TaskResource(ModelResource):
    subtasks = fields.ToManyField('self', 'task_set', full=True, readonly=True)

    parent_milestone = fields.ToOneField(MilestoneResource, 'parent_milestone', null=True, full=False)
    parent_task = fields.ToOneField('self', 'parent_task', null=True, full=False)

...

    def obj_update(self, bundle, **kwargs):
        bundle = super(TaskResource, self).obj_update(bundle, **kwargs)

        bundle.data['name'] = "test"
        bundle.data['parent_milestone'] = None <-- error here

        return self.obj_create(bundle, **kwargs)

While updating a see the the name is updated (any updated object getting the name "test").

But when updating the parent_milestone I get this error:

"'NoneType' object has no attribute 'parent_milestone'"

Any help please?


Solution

  • First you are doing a obj_update with super and after an obj_create, is that what you are expecting?

    In the case you want just to update and override the parent_milestone, you can do:

    class TaskResource(ModelResource):
        ....
        def obj_update(self, bundle, **kwargs):
    
            bundle.data['name'] = "test"
            bundle.data['parent_milestone'] = None  # now this will be override
    
            return super(TaskResource, self).obj_update(bundle, **kwargs)