1

Есть 2 аппликейшена

# app_places
from django.db import models
class Place(models.Model):
    movie = models.ManyToManyField('app_shows_and_times.Show', through='app_shows_and_times.Showtime')
    place_name = models.CharField(max_length=50, db_index=True)
    place_street = models.CharField('Street', max_length=80)
    place_phone = models.CharField('Phone', max_length=60)
    class Meta:
        db_table = 'place'

и

# app_shows_and_times
from django.db import models

class Show(models.Model):
    show_name = models.CharField(max_length=100, db_index=True)
    class Meta:
        db_table = 'show'
class Showtime(models.Model):
    showtime_dates = models.CharField('Date', max_length=30)
    showtime_times = models.CharField('Time', max_length=30)
    showtime_place = models.ForeignKey('app_places.Place', verbose_name='Place')
    showtime_show = models.ForeignKey(Show, verbose_name='Show name')
    class Meta:
        db_table = 'showtime'

makemigrations каждой из них проходит на ОК. Делаю migrate и выдает вот такое:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/antonio/projects/my_site/lib/python3.4/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/home/antonio/projects/my_site/lib/python3.4/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/antonio/projects/my_site/lib/python3.4/site-packages/django/core/management/base.py", line 393, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/antonio/projects/my_site/lib/python3.4/site-packages/django/core/management/base.py", line 444, in execute
    output = self.handle(*args, **options)
  File "/home/antonio/projects/my_site/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 146, in handle
    plan = executor.migration_plan(targets)
  File "/home/antonio/projects/my_site/lib/python3.4/site-packages/django/db/migrations/executor.py", line 59, in migration_plan
    for migration in self.loader.graph.forwards_plan(target):
  File "/home/antonio/projects/my_site/lib/python3.4/site-packages/django/db/migrations/graph.py", line 139, in forwards_plan
    self.ensure_not_cyclic(node, lambda x: (parent.key for parent in self.node_map[x].parents))
  File "/home/antonio/projects/my_site/lib/python3.4/site-packages/django/db/migrations/graph.py", line 196, in ensure_not_cyclic
    raise CircularDependencyError(", ".join("%s.%s" % n for n in cycle))
django.db.migrations.graph.CircularDependencyError: app_shows_and_times.0001_initial, app_places.0001_initial

Если обе модели сливаю в один файл, migrate проходит на ура. Но я не хочу сливать эти 2 аппликейшена в один файл.

Если закомментировать

movie = models.ManyToManyField('app_shows_and_times.Show', through='app_shows_and_times.Showtime')

тоже все проходит замечательно. Вроде все сделал по букварю.

Добавлены миграции

# app_place
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations


class Migration(migrations.Migration):

    dependencies = [
        ('app_shows_and_times', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Place',
            fields=[
                ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
                ('place_name', models.CharField(db_index=True, max_length=50)),
                ('place_street', models.CharField(verbose_name='Street', max_length=80)),
                ('place_phone', models.CharField(verbose_name='Phone', max_length=60)),
                ('movie', models.ManyToManyField(to='app_shows_and_times.Show', through='app_shows_and_times.Showtime')),
            ],
            options={
                'db_table': 'place',
            },
        ),
    ]

и

#app_shows_and_times
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations


class Migration(migrations.Migration):

    dependencies = [
        ('app_places', '__first__'),
    ]

    operations = [
        migrations.CreateModel(
            name='Show',
            fields=[
                ('id', models.AutoField(serialize=False, auto_created=True, primary_key=True, verbose_name='ID')),
                ('show_name', models.CharField(max_length=100, db_index=True)),
            ],
            options={
                'db_table': 'show',
            },
        ),
        migrations.CreateModel(
            name='Showtime',
            fields=[
                ('id', models.AutoField(serialize=False, auto_created=True, primary_key=True, verbose_name='ID')),
                ('showtime_dates', models.CharField(max_length=30, verbose_name='Date')),
                ('showtime_times', models.CharField(max_length=30, verbose_name='Time')),
                ('showtime_place', models.ForeignKey(to='app_places.Place', verbose_name='Place')),
                ('showtime_show', models.ForeignKey(to='app_shows_and_times.Show', verbose_name='Show name')),
            ],
            options={
                'db_table': 'showtime',
            },
        ),
    ]
2
  • Покажите содержимое файлов миграций
    – amirr
    13 сен 2015 в 6:58
  • @amirr, готово. 13 сен 2015 в 9:45

2 ответа 2

0

Попробуйте создать новую миграцию в app_place/migrations/0002_new_migration.py

# app_place
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations


class Migration(migrations.Migration):

    dependencies = [
        ('app_shows_and_times', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Place',
            fields=[
                ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
                ('place_name', models.CharField(db_index=True, max_length=50)),
                ('place_street', models.CharField(verbose_name='Street', max_length=80)),
                ('place_phone', models.CharField(verbose_name='Phone', max_length=60)),
                ('movie', models.ManyToManyField(to='app_shows_and_times.Show', through='app_shows_and_times.Showtime')),
            ],
            options={
                'db_table': 'place',
            },
        ),
    ]

А в app_place/migrations/0001_initial.py

# app_place
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations


class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
    ]
1
  • правильно я понимаю последовательность. 1) Меняю 0001_initial.py, 2) делаю migrate, 3) потом добавляю 0002_initial.py 4) еще раз делаю migrate? Если это правильная последовательность, то Rendering model states... DONE Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying app_places.0001_initial... OK Applying app_shows_and_times.0001_initial... File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) ValueError: Related model 'app_places.Place' cannot be resolved это на шаге №2 эррорит 14 сен 2015 в 20:42
0

Проблема "Циклическая зависимость" для Django 1.8.4 при использовании ManyToMany+through возникает тогда, когда в through указываем модель другого приложения. Для решения нашей проблемы нужно "поиграть" с makemigrations

1. В моем случае комментируем строку movie
# app_places
from django.db import models
class Place(models.Model):
    #movie = models.ManyToManyField('app_shows_and_times.Show', through='app_shows_and_times.Showtime')
    place_name = models.CharField(max_length=50, db_index=True)
    place_street = models.CharField('Street', max_length=80)
    place_phone = models.CharField('Phone', max_length=60)
    class Meta:
        db_table = 'place'

2. makemigrations app_place
3. makemigrations app_shows_and_times
4. Убираем комментарий со строки `movie = models.ManyToManyField('app_shows_and_times.Show', through='app_shows_and_times.Showtime')`
5. еще раз делаем makemigrations app_place
6. migrate

Это все.

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.