使用 Django,如何添加引用同一个表的外键列? [复制]
Posted
技术标签:
【中文标题】使用 Django,如何添加引用同一个表的外键列? [复制]【英文标题】:Using Django, how do I add a foreign key column that references the same table? [duplicate] 【发布时间】:2017-02-13 12:43:41 【问题描述】:我希望一个表包含一个外键字段,并尝试了以下代码:
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)
这会产生以下错误:
$ ./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】:根据https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey:
要创建递归关系(与自身具有多对一关系的对象),请使用 models.ForeignKey('self', on_delete=models.CASCADE)。
上面的代码应该改成:
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class CollectionModel(models.Model):
parent = models.ForeignKey('self', on_delete=models.CASCADE)
【讨论】:
【参考方案2】:您需要将以下行添加到模型的
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)
【讨论】:
以上是关于使用 Django,如何添加引用同一个表的外键列? [复制]的主要内容,如果未能解决你的问题,请参考以下文章