[Answered ]-Django – How to do complex query with left join and coalesce?

1πŸ‘

βœ…

The code is not syntetically correct, you can’t use <= inside a method signature, ie use that in filter(), also you need to pass the arguments before passing the keyword arguments through the function, ie some_function(a, b, x=y).

But, you can use Coalesce to annotate the value with Voucher queryset then run the filter again, like this:

query = Voucher.objects.filter(
        Q(customer_id = customer_id_input ) | Q(is_global = True),
        start_at__lte = now,
        end_at__gte = now,
        is_active = True,
        times_used__lt = F('usage_limit'),
        times_used_daily__lt = F('usage_limit_daily'),
        code__customer_id = customer_id_input
    ).annotate(
        usage_so_far=Coalesce('code__times_used', Value(0))
    ).filter(
        usage_so_far__gte=F('usage_limit_per_customer')
    ).order_by('created_at').values()
πŸ‘€ruddra

Leave a comment