Can I have a Django model that has a foreign key r

2019-01-14 10:29发布

Okay, how would I do this?

class Example(models.Model):
  parent_example = models.ForeignKey(Example)

I want to have a model have a foreign key reference to itself. When I try to create this I get a django validation error that Example is not yet defined.

3条回答
Deceive 欺骗
2楼-- · 2019-01-14 11:03

You should use

models.ForeignKey('self')

as mentioned here.

查看更多
Emotional °昔
3楼-- · 2019-01-14 11:06

Yes, just do this:

class Example(models.Model):
  parent_example = models.ForeignKey('self')
查看更多
Evening l夕情丶
4楼-- · 2019-01-14 11:12

You can do this using quotes too:

class Example(models.Model):
    parent_example = models.ForeignKey('Example')
查看更多
登录 后发表回答