Created
January 18, 2017 14:49
-
-
Save JoseKilo/12cfe8e65c428a745d89840fb810ccd0 to your computer and use it in GitHub Desktop.
Django primary-secondary relationship top list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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