gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:33:49 24 4
gpt4 key购买 nike

<分区>

我想要一个表自身包含一个外键字段,并尝试了以下代码:

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

如何将外键包含到与字段相同的表中?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com