我不知道为什么这不能按预期工作。
我在歌曲和周之间存在多对多关系,这些关系统一在位置模型中,该模型存储了歌曲的位置本周。
在视图中,我试着看看本周的一首歌是否在last_week中,但它表示它永远不会,这不是预期的结果。
型号:
class Song(models.Model):
name = models.CharField(max_length=300)
artist = models.CharField(max_length=300)
def __unicode__(self):
return self.name
class Week(models.Model):
date = models.DateField()
songs = models.ManyToManyField('Song', through="Position")
def __unicode__(self):
return unicode(self.date)
class Position(models.Model):
week = models.ForeignKey('Week')
song = models.ForeignKey('Song')
position = models.SmallIntegerField();
def __unicode__(self):
return unicode(self.week.date) + " " + unicode(self.song.name)
查看:
def changed_since_last_week(request):
week = Week.objects.all().reverse()[0]
last_week = Week.objects.all().reverse()[1]
songs = week.songs.all()
last_week_songs = last_week.songs.all()
context_dict = {"songs": songs}
for song in songs:
if song in last_week_songs: #This never gets executed!
song.change = Position.objects.get(week=last_week,song=song).position-Position.objects.get(week=week,song=song).position
else:
song.attr = "New entry"
return render(request, 'charts/change.html', context_dict)
外壳:
>>> song = Week.objects.all()[0].songs.all()[0]
>>> song
<Song: Uptown Funk!>
>>> song in Week.objects.all()[1].songs.all()
False
>>> Week.objects.all()[1].songs.all()
[<Song: Blank Space>, <Song: Uptown Funk!>'...(remaining elements truncated)...']
>>>
答案 0 :(得分:1)
我认为这部分不是问题所在。您没有在Week
上定义任何排序,因此您无法保证获得正确的周对象。在.order_by('-date')
班级中使用ordering
或定义Meta
。
x in y
包含具有相同具体模型的模型True
和y
,则 x.pk is not None
会返回x.pk == y.pk
。