не могу импортировать имя 'модель' из 'app.model' - PullRequest
0 голосов
/ 24 октября 2019

У меня есть два приложения 'user' и 'game', и вот мой user / models.py:

from django.db import models
from django.db.models.fields import related
from django.contrib.auth.models import AbstractBaseUser , User, 
 AbstractUser , PermissionsMixin
from .managers import CustomUserManager
from game.models import Game


class User(AbstractBaseUser,PermissionsMixin):
    username = models.CharField(max_length=150, 
                unique=True, blank=True , null=True,)
    email = models.EmailField( blank=True , null=True , unique=True)
    password = models.CharField(max_length=100, null=True , blank=True)


    objects = CustomUserManager()

    class Meta:
            db_table = 'user'


class Team(models.Model):
    name = models.CharField(max_length=40, unique=True)
    players = models.ManyToManyField(User, 
           related_name="players")
    game = models.ManyToManyField(Game)
    is_verfied = models.BooleanField(default=False)

    class Meta:
        db_table = 'team'

, а вот моя игра / models.py:

from django.db import models
from user.models import User, Team
from leaga.settings import AUTH_USER_MODEL

class Game(models.Model):
    name = models.CharField(max_length=50)
    is_multiplayer = models.BooleanField(default=False)

class Event(models.Model):
    title = models.CharField(max_length=100)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()


class Tournament(models.Model):
    title = models.CharField(max_length=50)
    is_team = models.BooleanField(default=False)
    price = models.PositiveIntegerField()
    info = models.TextField(max_length=1000)
    user = models.ManyToManyField(AUTH_USER_MODEL,
    related_name='tounament_user')
    team = models.ManyToManyField(Team, related_name='team')
    game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='tournament_game')
    event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='tournament_event')

    # some other code and classes here but unnecessary to mention

. ,,,когда я запускаю:

 python manage.py makemigrations user

это журнал консоли:

 Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute
django.setup()
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate
app_config.import_models()
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/amir/Desktop/leaga/leaga/user/models.py", line 6, in <module>
from game.models import Game
File "/Users/amir/Desktop/leaga/leaga/game/models.py", line 3, in <module>
from user.models import Team
ImportError: cannot import name 'Team' from 'user.models' (/Users/amir/Desktop/leaga/leaga/user/models.py)

Я пытался удалить все файлы .pyc из моего проекта

, а также удалить всебазу данных и создать заново (я знаю, что это, вероятно, не главное, но я разозлился, и я отбросил всю базу данных и воссоздал ее

1 Ответ

1 голос
/ 24 октября 2019

Файл "/Users/amir/Desktop/leaga/leaga/user/models.py", строка 6, в

из game.models import Game

File "/Users/amir/Desktop/leaga/leaga/game/models.py ", строка 3, в

из user.models import Team

ImportError: невозможно импортировать имя 'Team' from 'user.models '(/Users/amir/Desktop/leaga/leaga/user/models.py)

Из сообщения видно, что это связано с циклическим импортом.

user/models.py пытается импортировать модель Game из game/models.py, а game/models.py пытается импортировать модель Team из user/models.py.


Одно решениеэто удалить:

from game.models import Game

С user/models.py и изменить:

game = models.ManyToManyField(Game)

На:

game = models.ManyToManyField('game.Game')

Возможно, вы захотите прочитать: ForeignKey и ManyToManyField .

Соответствующая часть скопирована здесь:

Если вам нужно создать связь на модели, которая еще не былаВы можете использовать имя модели, а не сам объект модели:

...