如何在django中实例化递归外键?

时间:2018-03-12 07:36:58

标签: django django-models foreign-keys

class Notebook(models.Model):
    title=models.CharField(max_length=10)
    father = models.ForeignKey('self', on_delete=models.CASCADE)

如何使用它?

n1=Notebook(title='a', father='???')  
n2=Notebook(title='b', father=n1)

如何设置n1的父属性值?

1 个答案:

答案 0 :(得分:1)

试试这个,

class Notebook(models.Model):
    title = models.CharField(max_length=10)
    father = models.ForeignKey('self', default=None, null=True, blank=True, on_delete=models.CASCADE)  # change is here <<


parent = Notebook.objects.create(title="some title")
child = Notebook.objects.create(title='child title', parent=parent)