Skip to content

Instantly share code, notes, and snippets.

@mazlum
Last active June 3, 2019 14:28
Show Gist options
  • Save mazlum/06a0dc5d8abb6b6b413d1ffa2c8db20c to your computer and use it in GitHub Desktop.
Save mazlum/06a0dc5d8abb6b6b413d1ffa2c8db20c to your computer and use it in GitHub Desktop.
Django making queries
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=30)
class Exam(models.Model):
name = models.ForeignKey(Student, on_delete=models.CASCADE)
point = models.PositiveIntegerField(default=0)
from django.db.models import Case, IntegerField, Sum, Value, When
from django.db.models.functions import Coalesce
q = Exam.objects.aggregate(
success=Coalesce(
Sum(
Case(
When(score__gte=85, then=Value(1)),
default=Value(0),
output_field=IntegerField(),
)
),
Value(0),
),
)
print(q)
# {"success": 5}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment