#python #django #model #foreign-keys #one-to-one
#python #django #Модель #внешние ключи #один к одному
Вопрос:
Я пытаюсь создать модель, которая нуждается в соотношении один к одному с исходным материалом, который используется множеством формул. Это мой код:
from django.db import models
from dashboard.models import Formulas, Feedstock
class FeedstockFormulas(models.Model):
ratio = models.FloatField()
feedstock = models.OneToOneField(Feedstock, on_delete=models.CASCADE, default="0")
formulas = models.ForeignKey(Formulas, on_delete=models.CASCADE)
Это ошибка, которую я получаю:
Traceback (most recent call last):
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 798, in __init__
to._meta.model_name
AttributeError: module 'dashboard.models.Feedstock' has no attribute '_meta'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute
django.setup()
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate
app_config.import_models()
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/mnt/c/Users/isaac/Documents/Github/uniaoracoes/dashboard/models/__init__.py", line 1, in <module>
from .Formulas import Formulas
File "/mnt/c/Users/isaac/Documents/Github/uniaoracoes/dashboard/models/Formulas.py", line 2, in <module>
from dashboard.models import FeedstockFormulas
File "/mnt/c/Users/isaac/Documents/Github/uniaoracoes/dashboard/models/FeedstockFormulas.py", line 4, in <module>
class FeedstockFormulas(models.Model):
File "/mnt/c/Users/isaac/Documents/Github/uniaoracoes/dashboard/models/FeedstockFormulas.py", line 6, in FeedstockFormulas
feedstock = models.OneToOneField(Feedstock, on_delete=models.CASCADE, default="0")
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 1049, in __init__
super().__init__(to, on_delete, to_field=to_field, **kwargs)
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 800, in __init__
assert isinstance(to, str), (
AssertionError: OneToOneField(<module 'dashboard.models.Feedstock' from '/mnt/c/Users/isaac/Documents/Github/uniaoracoes/dashboard/models/Feedstock.py'>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'
Я действительно не могу ее решить, поскольку первый параметр ForeignKey уже является моделью…
Ответ №1:
Похоже, что это побочный продукт циклического импорта где-то.
Попробуйте изменить на
feedstock = models.OneToOneField("dashboard.Feedstock", on_delete=models.CASCADE, default="0")
formulas = models.ForeignKey("dashboard.Formulas", on_delete=models.CASCADE)
Комментарии:
1. Это исправило мою подсказку (не ошибку), в которой говорилось, что ForeignKey (unique = True) совпадает с OneToOneField. После замены ForeignKey на OneToOneField в моих моделях это сработало.