2

I have two simple tables in Django which looks like:

class Session(models.Model):
    id = models.AutoField(primary_key=True)

class Track(models.Model):
    id = models.AutoField(primary_key=True)
    session = models.ForeignKey(Session)
    when = models.DateTimeField(null=False, auto_now_add=True)

I need to find a the average duration of all the sessions. The duration of a session is calculated by subtracting the highest when value with the lowest when value. Can I do something like this:

Session.objects.all().annotate(duration=Max('track__when') - Min('track__when')).aggregate(Avg('duration'))

Any better methods?

Thanks.

Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382

1 Answers1

1

As I already answered you the same question in Querying data from Django , you can't do using only the ORM API, either:

  1. you extend the API by defining your custom annotations, or
  2. you do part of the algorithm in python, in your view/templatetag/whatever
Community
  • 1
  • 1
rewritten
  • 16,280
  • 2
  • 47
  • 50