django – 从结果中排除整个QuerySet

前端之家收集整理的这篇文章主要介绍了django – 从结果中排除整个QuerySet前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下型号:
class LibraryEntry(models.Model):
   player = models.ForeignKey(Player)
   player_lib_song_id = models.IntegerField()
   title = models.CharField(max_length=200)
   artist = models.CharField(max_length=200)
   album = models.CharField(max_length=200)
   track = models.IntegerField()
   genre = models.CharField(max_length=50)
   duration = models.IntegerField()
   is_deleted = models.BooleanField(default=False)

   class Meta:
     unique_together = ("player","player_lib_song_id")

   def __unicode__(self):
     return "Library Entry " + str(self.player_lib_song_id) + ": " + self.title

 class BannedSong(models.Model):
   lib_entry = models.ForeignKey(LibraryEntry)

   def __unicode__(self):
     return "Banned Library Entry " + str(self.lib_entry.title)

我想做这样的查询

banned_songs = BannedSong.objects.filter(lib_entry__player=activePlayer)
 available_songs = LibraryEntry.objects.filter(player=activePlayer).exclude(banned_songs)

基本上如果一首歌被禁止,我想把它从我的可用歌曲中排除.有没有办法在Django中这样做?

解决方法

banned_song_ids = (BannedSong.objects.filter(lib_entry__player=activePlayer)
                                            .values_list('lib_entry',flat=True))

available_songs = (LibraryEntry.objects.filter(player=activePlayer)
                                            .exclude('id__in' = banned_song_ids))

替代方案是:

available_songs = (LibraryEntry.objects.filter(player=activePlayer)
                                          .filter(bannedsong__isnull = True))
原文链接:https://www.f2er.com/python/186076.html

猜你在找的Python相关文章