0

使用以下 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]或其他位置组合进行过滤。Position.objects.get(id=3)在这个例子中,我想要一个所有玩 1B (ie ) 或 3B (ie )的玩家的列表Position.objects.get(id=5)。我该怎么做呢?

回答:

Player.objects.filter(positions__id__in=[3,5])

第二个答案,因为__id是不必要的:

Player.objects.filter(positions__in=[3,5])

任何其他评论都会很棒。谢谢,代码太累了

4

1 回答 1

3
players = Player.objects.filter(positions__pk__in=[3,5])
于 2013-10-15T21:15:13.167 回答