我有一个班级
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>
即使这两个对象相同。
这里有什么我想念的吗?
答案 0 :(得分:15)
assertEqual()
使用==
运算符来比较类。用户定义类的默认==
运算符按对象标识比较实例。这意味着当两个实例是相同的实例时,它们才被视为相等。
答案 1 :(得分:4)
比较型号id或pk,它会没问题。
答案 2 :(得分:3)
AssertionError
是正确的。您的get_playlist_with_id
会返回Queryset
而不是Playlist
个实例。如果您希望get_playlist_with_id
返回单个实例,则应使用get
而不是filter
。