1

我继承了一个大型 Django 应用程序,它在“shows”应用程序的模型中使用了这个习语:

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”方法,因为“ManyToManyField ...”规范已经创建了shows_movie_playlist_players。到 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")

那么这是一个正确指定的关系和覆盖的表,它还不支持测试,还是有什么可怕的错误?

谢谢阅读!

4

1 回答 1

1

哦哇...我对你有感觉:) 是的,这是非常错误的,但它可能有一个简单的解决方案。基本上它是一个试图完成“通过”功能的黑客ManyToManyField

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

于 2012-04-10T21:24:30.490 回答