How to query previous items of a given criteria

Viewed 57

Here is the model

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)

The implementation:

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)

Now how can i query the previous is_scored=False if a given ShootingAttempt where pk=5 assumed for attempt5 by Player named Micheal Jordan? This will yield the result of: [attempt4]

Means jordan has 1 miss before successfully dig 3 points in 5th attempt

If the given ShootingAttempt where pk=3 (attempt3) this will return

[attempt1, attempt2] 

Means that Jordan has 2 misses before successfully dig the first 3 points

And if pk=6 is given it will return nothing because there is no is_scored=False between the last is_scored=True and the pk=6 (attempt6)

Means that jordan has no miss of before digging another 3 points

Every shooting attempt may miss and i would like to get the last misses of every successful attempt.

Is there any work around?

3 Answers
Related