Tastypie foreign key set null

114 Views Asked by At

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?

1

There are 1 best solutions below

1
On BEST ANSWER

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)