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.

Revisions

  1. mazlum renamed this gist Jun 3, 2019. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. mazlum revised this gist Jun 3, 2019. 1 changed file with 0 additions and 18 deletions.
    18 changes: 0 additions & 18 deletions queries.py
    Original file line number Diff line number Diff line change
    @@ -1,18 +0,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}
  3. mazlum revised this gist Jun 3, 2019. 1 changed file with 1 addition and 4 deletions.
    5 changes: 1 addition & 4 deletions models.py
    Original file line number Diff line number Diff line change
    @@ -1,10 +1,7 @@
    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)
    studen_name = models.CharField(max_lenght=50)
    point = models.PositiveIntegerField(default=0)

  4. mazlum revised this gist Jun 3, 2019. 1 changed file with 18 additions and 0 deletions.
    18 changes: 18 additions & 0 deletions queries.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    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}
  5. mazlum created this gist Jun 3, 2019.
    10 changes: 10 additions & 0 deletions models.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    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)