Skip to content

Instantly share code, notes, and snippets.

@sanjaykrishnan
Created May 29, 2019 19:24
Show Gist options
  • Save sanjaykrishnan/0e0d7388c18d6c2a5c55fc492ae5d80a to your computer and use it in GitHub Desktop.
Save sanjaykrishnan/0e0d7388c18d6c2a5c55fc492ae5d80a to your computer and use it in GitHub Desktop.
subquery
from django.db.models import OuterRef, Subquery
unique_users_query = (CouponApplication
.objects
.all()
.filter(coupon=OuterRef('id'))
.values('user_id') # group cities by state
.order_by() # reset ordering
.annotate(cnt=Count('*'))
.values('cnt')[:1] # Only have 1 row & 1 value allowed
)
Coupon.objects.all()
.annotate(
unique_users_count=Subquery(
city_query,
output_field=models.IntegerField()
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment