使用Django,如何添加引用同一个表的外键列?

时间:2016-10-05 07:20:59

标签: python django database

我想要一个表来为自己包含一个foriegn键字段,并尝试了以下代码:

self.layoutIfNeeded()
yourButton.layer.cornerRadius = self.frame.height / 2.0
yourButton.layer.borderWidth = 2.0

这会产生以下错误:

from __future__ import unicode_literals

from django.db import models

# Create your models here.

class CollectionModel(models.Model):
    parent = models.ForeignKey(CollectionModel, on_delete=models.CASCADE)

如何将foriegn键作为字段包含在同一个表中?

2 个答案:

答案 0 :(得分:2)

根据https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey

  

要创建递归关系 - 与自身具有多对一关系的对象 - 请使用 models.ForeignKey('self',on_delete = models.CASCADE)

以上代码应更改为:

$ ./manage.py makemigrations eav
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
    utility.execute()
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute
    django.setup()
File "/usr/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
File "/usr/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
File "/usr/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
File "/home/username/Documents/devel/python/project/eav/models.py", line 7, in <module>
    class CollectionModel(models.Model):
File "/home/username/Documents/devel/python/project/eav/models.py", line 8, in CollectionModel
    parent = models.ForeignKey(CollectionModel, on_delete=models.CASCADE)
NameError: name 'CollectionModel' is not defined

答案 1 :(得分:0)

您需要将以下行添加到模型的

parent = models.ForeignKey('self', blank=True, null=True)

所以,你的模型看起来像,

from __future__ import unicode_literals

from django.db import models

# Create your models here.

class CollectionModel(models.Model):
    parent = models.ForeignKey('self', blank=True, null=True)