Search code examples
djangodjango-querysetdjango-aggregation

Average calculated on the difference on a Min and Max value in Django


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.


Solution

  • 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