如何删除外键?
我有两个模型:
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
。
答案 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)