gpt4 book ai didi

python - 如何查询给定条件的先前项目

转载 作者:行者123 更新时间:2023-11-28 18:20:52 25 4
gpt4 key购买 nike

这是模型

class Player(models.Model):
name = models.CharField()

class ShootingAttempt(models.Model):
player = models.ForeignKey(Player, related_name='shooting_attempts')
is_scored = models.BooleanField()
point = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_add_now=True)

实现:

jordan = Player.objects.create(name='Michael Jordan')

attempt1 = ShootingAttempt(player=jordan, is_scored=False)
attempt2 = ShootingAttempt(player=jordan, is_scored=False)
attempt3 = ShootingAttempt(player=jordan, is_scored=True, point=3)

attempt4 = ShootingAttempt(player=jordan, is_scored=False)
attempt5 = ShootingAttempt(player=jordan, is_scored=True, point=3)
attempt6 = ShootingAttempt(player=jordan, is_scored=True, point=3)

现在,如果给定的 ShootingAttempt 假设 pk=5 为 attempt5 的玩家名为 ,我该如何查询之前的 is_scored=False >迈克尔·乔丹?这将产生以下结果:[attempt4]

表示乔丹在第 5 次尝试成功拿到 3 分之前有 1 次失误

如果给定的 ShootingAttempt 其中 pk=3 (attempt3) 这将返回

[attempt1, attempt2] 

意味着乔丹在成功拿到前 3 分之前有 2 次失误

如果给定 pk=6,它不会返回任何内容,因为没有 is_scored=False 在最后一个之间 is_scored=Truepk=6 (attempt6)

意味着乔丹在再挖3分之前没有失误

每次射击尝试都可能失手,我希望每次成功尝试都能得到最后的失误。

有解决办法吗?

最佳答案

这些是我更喜欢的步骤。

获取您想要的 is_scored=True ShootingAttempt 实例的 id。说 id1

并且您可以使用 .filter(id__lt=id1).aggregate(id2=Max('id')) 获得另一个 is_scored=True ShootingAttempt 实例这将返回您 {id2: some_id},它具有 is_scored=True 并且低于 id1。

id2 = ShootingAttempt.objects.all().filter(id__lt=id1).aggregate(id2=Max('id'))['id2']

最后你可以 - .filter(id__gt=id2).filter(id__lte=id1) 它将返回带有 False 和最后一个 True< 的查询集.

关于python - 如何查询给定条件的先前项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45181841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com