Tastypie 外键设置为空

Tastypie foreign key set null

我需要在更新对象时将外键设置为空。

这是模型:

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

这是 tastypie 资源:

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)

在更新时看到名称被更新(任何更新的对象获得名称 "test")。

但是在更新 parent_milestone 时出现此错误:

"'NoneType' 对象没有属性 'parent_milestone'"

有什么帮助吗?

首先,您使用 super 执行 obj_update,然后执行 obj_create,这是您期望的吗?

如果您只想更新和覆盖 parent_milestone,您可以这样做:

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)