Skip to content

Instantly share code, notes, and snippets.

@JoseKilo
Created January 18, 2017 14:49
Show Gist options
  • Save JoseKilo/12cfe8e65c428a745d89840fb810ccd0 to your computer and use it in GitHub Desktop.
Save JoseKilo/12cfe8e65c428a745d89840fb810ccd0 to your computer and use it in GitHub Desktop.
Django primary-secondary relationship top list
from __future__ import unicode_literals
from django.db import models
class Main(models.Model):
name = models.TextField()
class Son(models.Model):
name = models.TextField()
date = models.DateTimeField(auto_now_add=True)
main = models.ForeignKey(Main, related_name='sons')
value = models.IntegerField()
from datetime import timedelta
from django.db.models import Avg, Case, FloatField, Value, When
from django.db.models.functions import Coalesce, Now
from models import *
queryset = Main.objects.all().annotate(
avg=Coalesce(
Avg(Case(When(sons__date__gt=Now() - timedelta(days=1),
then='sons__value'),
default=Value(None),
output_field=FloatField())),
Value(0))).order_by('-avg').values('name', 'avg')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment