从以下django模型开始工作:
class Position(models.Model):
# pos_list in order ('P', 'C', '1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF')
# pos id / pk correspond to index value of pos_list.index(pos)
pos = models.CharField(max_length=2)
class Player(models.Model):
name = models.CharField(max_length=100)
positions = models.ManyToManyField(Position, through='PlayerPosition')
class PlayerPosition(models.Model):
player = models.ForeignKey(Player)
position = models.ForeignKey(Position)
primary = models.BooleanField()
如果我有一个位置ID列表,例如[3, 5]
,其中Position.objects.filter(id__in=[3,5])
会生成['1B', '3B']
,我希望能够通过Player.objects.all()
的position_id列表或其他一些职位组合过滤[3, 5]
。在这个例子中,我想要一个播放1B(即Position.objects.get(id=3)
)或3B(即Position.objects.get(id=5)
)的所有玩家的列表。我该怎么做?
解答:
Player.objects.filter(positions__id__in=[3,5])
第二个答案,因为__id
是不必要的:
Player.objects.filter(positions__in=[3,5])
任何其他评论都会很棒。谢谢,太累了代码
答案 0 :(得分:1)
players = Player.objects.filter(positions__pk__in=[3,5])