1

I have a simple hierarchic model whit a Person and RunningScore as child. this model store data about running score of many user, simplified something like:

class Person(models.Model):
   firstName = models.CharField(max_length=200)
   lastName = models.CharField(max_length=200)  

class RunningScore(models.Model):
   person = models.ForeignKey('Person', related_name="scores")
   time = models.DecimalField(max_digits=6, decimal_places=2)   

If I get a single Person it cames with all RunningScores associated to it, and this is standard behavior. My question is really simple: if I'd like to get a Person with only a RunningScore child (suppose the better result, aka min(time) ) how can I do? I read the official Django documentation but have not found a solution.

Fabrizio
  • 53
  • 1
  • 8

2 Answers2

0

I am not 100% sure if I get what you mean, but maybe this will help:

from django.db.models import Min
Person.objects.annotate(min_running_time=Min('time'))

The queryset will fetch Person objects with min_running_time additional attribute.

You can also add a filter:

Person.objects.annotate(min_running_time=Min('time')).filter(firstName__startswith='foo')

Accessing the first object's min_running_time attribute:

first_person = Person.objects.annotate(min_running_score=Min('time'))[0]
print first_person.min_running_time

EDIT:

You can define a method or a property such as the following one to get the related object:

class Person(models.Model):
...
    @property
    def best_runner(self):
        try:
            return self.runningscore_set.order_by('time')[0]
        except IndexError:
            return None
miki725
  • 27,207
  • 17
  • 105
  • 121
shanyu
  • 9,536
  • 7
  • 60
  • 68
  • Yes, Your solution it's correct if I need only the best running time but I need the whole Child object and not only "time" field. – Fabrizio Jun 06 '11 at 08:30
  • Your solution is was I looking for. I make a little modification: def best_runner(self): – Fabrizio Jun 07 '11 at 14:39
0

If you want one RunningScore for only one Person you could use odering and limit your queryset to 1 object. Something like this:

Person.runningscore_set.order_by('-time')[0]

Here is the doc on limiting querysets:

https://docs.djangoproject.com/en/1.3/topics/db/queries/#limiting-querysets

Facundo Casco
  • 10,065
  • 8
  • 42
  • 63