检查对象是否在另一个查询集中?

Check if object is in another queryset?

我不明白为什么这不能按预期工作。

我在songsweeks之间有一个多对多的关系,统一在一个position 存储一周歌曲位置的模型。

在视图中,我尝试查看本周的歌曲是否在 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)

Shell:

>>> 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)...']
>>> 

我不认为那部分是问题所在。您没有在 Week 上定义任何顺序,因此您无法保证获得正确的星期对象。在 Meta class.

中使用 .order_by('-date') 或定义 ordering

x in y returns True 如果 y 包含具有相同具体模型的模型,x.pk is not Nonex.pk == y.pk