如何解除外键相关关系的绑定?

时间:2018-09-27 04:19:57

标签: python django django-rest-framework

如何删除外键?

我有两个模型:

class Child(models.Model):
    name = models.CharField(max_length=256, null=True, blank=True)
    parent = models.ForeignKey(to=Parent, null=True, related_name="children", on_delete=models.DO_NOTHING)


class Parent(models.Model):
    name = models.CharField(max_length=256, null=True, blank=True)

    def unbind_children(self):  # there I want to unbind all children
        # how to realize this? 

我想取消绑定孩子,这意味着我想使与父相关的特殊Child实例的父字段为None

1 个答案:

答案 0 :(得分:0)

尝试 self.children.update(parent=None)

class Parent(models.Model):
    name = models.CharField(max_length=256, null=True, blank=True)

    def unbind_child(self):
        self.children.update(parent=None)