Skip to content

Instantly share code, notes, and snippets.

@aasmpro
Created June 1, 2020 07:01
Show Gist options
  • Save aasmpro/8f0adf26ec998334d37da3637dfa57dc to your computer and use it in GitHub Desktop.
Save aasmpro/8f0adf26ec998334d37da3637dfa57dc to your computer and use it in GitHub Desktop.
django conditional annotate
class OrderQuerySet(models.QuerySet):
def annotate_sold_coupon(self):
sold_coupons = SoldCoupon.objects.filter(sell_code=OuterRef('sold_coupon__sell_code'))
return self.annotate(
sold_coupon__sell_code=Case(
When(site_id=2, then=Concat(Value('SNAPP-NEW-'), 'id')),
When(site_id=3, then=Concat(Value('TAP30-NEW-'), 'id')),
When(site_id=4, then=Concat(Value('T2BON-NEW-'), 'id'))
),
sold_coupon__exist=Exists(sold_coupons.values('is_used')),
sold_coupon__id=Subquery(sold_coupons.values('id')),
sold_coupon__is_used=Subquery(sold_coupons.values('is_used'))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment