迁移文件中的意外循环依赖性

时间:2017-04-21 14:01:47

标签: python django

Error - django.db.migrations.exceptions.CircularDependencyError: accounts.0001_initial, songs.0001_initial

我有两个应用帐户和歌曲。歌曲有两个模型文件 - models.py和song_metadata_models.py

accounts/models.py

class AppUser(models.Model):

  user = models.OneToOneField(User)

  user_languages = models.ManyToManyField('songs.SongLang')

  user_genres = models.ManyToManyField('songs.SongGenre')

  def __str__(self):
      return self.user.username

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

songs/song_metadata_models.py

class SongGenre(models.Model):

  short_name = models.CharField(max_length=10)

  full_name =  models.CharField(max_length=100)

  def __str__(self):
      return self.full_name

class SongLang(models.Model):    


  short_name = models.CharField(max_length=10)

  full_name =  models.CharField(max_length=100)

  def __str__(self):
      return self.full_name

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

songs/models.py

class Song(models.Model):

# Fields
  name = CharField(max_length=255)
  slug = AutoSlugField(populate_from='name', blank=True)
  created = DateTimeField(auto_now_add=True, editable=False)
  last_updated = DateTimeField(auto_now=True, editable=False)
  url = CharField(max_length=100)
  artist = CharField(max_length=50)
  album = CharField(max_length=50)
  like = BooleanField(default=False)
  dislike = BooleanField(default=False)

  # Relationship Fields
  requested_by = ForeignKey('accounts.AppUser', related_name='song_requested_by')
  dedicated_to = ManyToManyField('accounts.AppUser', null = True, blank = True,related_name='song_dedicated_to')
  recommended_to = ManyToManyField('accounts.AppUser', null = True, blank = True,related_name='song_recommended_to')

如何解决这个问题?在模型级别没有循环依赖,那么为什么会出现这个问题?

1 个答案:

答案 0 :(得分:1)

解决方案1:将AppUser的many2many移动到SongLang和SongGenre。默认情况下,m2m关系是syme​​tric,因此您可以在关系的任一侧声明它(nb:只需确保将related_name设置为在AppUser模型中命名字段的方式。)

解决方案2:将SongGenre和SongLang模型移动到第三个应用程序(循环依赖的规范解决方案)

解决方案3:最终尝试首先创建没有m2m字段的AppUser模型,创建初始迁移,然后添加m2m字段(不确定它是否会起作用)。