6

我有一堂课

class PlaylistManager(models.Manager):
    def add_playlist(self, name):
        playlist = Playlist(name=name)
        playlist.save()
        return playlist

    def get_playlist_with_id(self, id):
        return super(PlaylistManager, self).get_query_set().filter(pk=id)

class Playlist(models.Model):
    name = models.CharField(max_length=30)
    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)
    deleted = models.BooleanField(default=False)
    objects = PlaylistManager() # is a customer manager

    def __repr__(self):
        return '<Playlist name:%s, date_created:%s, date_modified:%s, deleted:%s>' % \
                (self.name, self.date_created, self.date_modified, self.deleted)

    class Meta:
        db_table = 'playlists'

test作为

def test_get_playlist(self):
    playlist = Utility.add_playlist()
    self.assertEqual(Playlist.objects.get_playlist_with_id(playlist.id), playlist)

class Utility():
    @staticmethod
    def add_playlist(playlist_name=PLAYLIST):
        return Playlist.objects.add_playlist(playlist_name)

当我运行测试时,我看到错误为

AssertionError: [<Playlist name:playlist, date_created:2012-07-18 19:54:12.265909+00:00, date_modified:2012-07-18 19:54:12.265955+00:00, deleted:False>] != <Playlist name:playlist, date_created:2012-07-18 19:54:12.265909+00:00, date_modified:2012-07-18 19:54:12.265955+00:00, deleted:False>

即使两个对象相同。

我在这里有什么遗漏吗?

4

3 回答 3

15

assertEqual()使用==运算符来比较类。==用户定义类的默认运算符按对象身份比较实例。这意味着两个实例仅在它们是相同实例时才被视为相等。

于 2012-07-18T20:04:41.423 回答
4

比较模型id或pk就可以了。

于 2012-07-18T20:06:12.330 回答
3

AssertionError是正确的。你get_playlist_with_id返回一个Queryset不是Playlist实例。如果要get_playlist_with_id返回单个实例,则应使用getnot filter

于 2012-07-18T20:22:49.037 回答