是否可以将django模型类与ManyToMany关系合并?

时间:2012-04-10 20:57:14

标签: python sql django django-models

我继承了一个大型的Django应用程序,它在“show”应用程序的模型中具有这个成语:

class Movie_Playlist(models.Model):
    name = models.CharField(max_length=150)
    # More fields here...

    players = models.ManyToManyField(
        User, related_name='playlists_played', null=True, blank=True)

class PlaylistPlayer(models.Model):
    user           = models.ForeignKey(User, related_name='play_links')
    movie_playlist = models.ForeignKey(Movie_Playlist, related_name='playlist_plays')
    count          = models.IntegerField(default=0)
    last_played    = models.DateTimeField(editable=False)

    class Meta:
        db_table = 'shows_movie_playlist_players'  

尽我所知,想法可能是shows_movie_playlist_players表(由ManyToManyField关系创建)应该通过存储除了关系本身之外的每用户信息来执行双重任务。当然,原始数据库中似乎只有两个相关的表:“shows_movie_playlist”和“shows_movie_playlist_players”。

另外,对于它的价值,这在Django 1.2.3 - 1.3.1中“验证”很好。

这一切都很好,但是当它尝试创建测试数据库时它会破坏“python manage.py test”方法,因为shows_movie_playlist_players已经由“ManyToManyField ...”规范创建了它到达PlaylistPlayer类的时间。

如果我注释掉“ManyToManyField ...”行,我可以创建测试数据库并运行测试没有问题。否则,我明白了:

> python manage test shows -v3
Creating test database for alias 'default' ('test_production')...
Creating tables ...
Creating table shows_movie_playlist_players
Creating table shows_movie_playlist
Creating table shows_movie_playlist_players
Traceback (most recent call last):
  File "manage.py", line 16, in <module>
    execute_manager(settings)
    ... Lots of tracebackage here...
_mysql_exceptions.OperationalError: (1050, "Table 'shows_movie_playlist_players' already exists")

这是一个正确指定的关系和被覆盖的表,它还没有支持测试,或者是一个非常错误的东西?

感谢阅读!

1 个答案:

答案 0 :(得分:1)

哇哇...我觉得对你:)是的,这是非常错的,但它可能有一个简单的解决方案。 基本上它是一个试图完成ManyToManyField

的“通过”功能的黑客

尝试指定through='shows.PlaylistPlayer' on the玩家`m2m字段,然后查看其行为。