Created
July 8, 2021 13:52
-
-
Save natronics/f6317797f7776ef3005aaa6ab39bb349 to your computer and use it in GitHub Desktop.
Django Annotate F Expression Zeros
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
SELECT | |
0 AS "zero_sum", | |
(0 + COUNT("pizza"."id")) | |
FROM "pizza" | |
zero_sum | complex_sum | |
--------- | ----------- | |
0 | 100 |
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 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) |
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
SELECT | |
0 AS "zero_sum", | |
0 AS "complex_sum" -- Short circuit to 0! | |
FROM "pizza" | |
zero_sum | complex_sum | |
--------- | ----------- | |
0 | 0 |
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 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