Django使用GenericForeignKey时遭遇AttributeError问题求助
Django中GenericForeignKey触发AttributeError的解决办法
问题场景
在VS Code开发Django项目,包含store和tag两个应用,尝试用GenericForeignKey建立标签与store应用中Product模型的关联。运行python manage.py runserver时报错:
AttributeError: module 'django.db.models' has no attribute 'GenericForeignKey'
同时VS Code中from django.contrib.contenttypes.fields import GenericForeignKey这行导入的文本颜色变浅。
原模型代码
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey # Create your models here. class Tag(models.Model): label = models.CharField(max_length=225) class TaggedField(models.Model): #what tag is applied to what object tag = models.ForeignKey(Tag, on_delete=models.CASCADE) #Type(product,viedo, article) #ID content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = models.GenericForeignKey()
完整报错信息
(storefront2) PS C:\Users\kesar\OneDrive\Desktop\storefront2> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1520.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1520.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\kesar\.virtualenvs\storefront2-hockpoA9\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\kesar\.virtualenvs\storefront2-hockpoA9\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\kesar\.virtualenvs\storefront2-hockpoA9\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\kesar\.virtualenvs\storefront2-hockpoA9\Lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\kesar\.virtualenvs\storefront2-hockpoA9\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\kesar\.virtualenvs\storefront2-hockpoA9\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\kesar\.virtualenvs\storefront2-hockpoA9\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\kesar\.virtualenvs\storefront2-hockpoA9\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1520.0_x64__qbz5n2kfra8p0\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\kesar\OneDrive\Desktop\storefront2\tags\models.py", line 11, in <module> class TaggedField(models.Model): File "C:\Users\kesar\OneDrive\Desktop\storefront2\tags\models.py", line 18, in TaggedField content_object = models.GenericForeignKey() ^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: module 'django.db.models' has no attribute 'GenericForeignKey'
解决方法
你已经正确从django.contrib.contenttypes.fields导入了GenericForeignKey,但在定义content_object字段时错误地使用了models.GenericForeignKey()——GenericForeignKey并不在django.db.models模块中,而是在你已经导入的django.contrib.contenttypes.fields里。
只需把字段定义改为直接使用导入的GenericForeignKey类即可,修复后的完整代码如下:
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey # Create your models here. class Tag(models.Model): label = models.CharField(max_length=225) class TaggedField(models.Model): # 标记关联的对象 tag = models.ForeignKey(Tag, on_delete=models.CASCADE) # 关联对象的类型(如Product、Video等) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # 关联对象的ID object_id = models.PositiveIntegerField() # 通用外键关联 content_object = GenericForeignKey()
这样修改后,重新运行python manage.py runserver即可正常启动服务,VS Code中导入语句的颜色也会恢复正常(因为导入的类被实际使用了)。
内容的提问来源于stack exchange,提问作者kesari devaraya
相关产品推荐
相关产品推荐

