Skip to content

Instantly share code, notes, and snippets.

@natronics
Created July 8, 2021 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natronics/f6317797f7776ef3005aaa6ab39bb349 to your computer and use it in GitHub Desktop.
Save natronics/f6317797f7776ef3005aaa6ab39bb349 to your computer and use it in GitHub Desktop.
Django Annotate F Expression Zeros
SELECT
0 AS "zero_sum",
(0 + COUNT("pizza"."id"))
FROM "pizza"
zero_sum | complex_sum
--------- | -----------
0 | 100
from django.db import models
# The exact model seems unimportant here, I'll mosly be counting and filtering by id
class Pizza(models.Model):
name = models.CharField(max_length=60)
price = models.models.DecimalField(decimal_places=2, max_digits=7)
description = models.TextField(null=True)
SELECT
0 AS "zero_sum",
0 AS "complex_sum" -- Short circuit to 0!
FROM "pizza"
zero_sum | complex_sum
--------- | -----------
0 | 0
from django.db.models import Q, F, Count
from models import Pizza
# This might come from a request for example, and could have values
# But here I'm interested in the empty case
list_of_ids = []
q = Pizza.objects.annotate(
zero_sum=Count('id', filter=Q(id__in=list_of_ids)),
complex_sum=F('zero_sum') + Count('id'),
)
print(q.query)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment