I'm working with django-eztables to do the server-side processing for a datatable, and I want to add some fields involving aggregation (as mentioned here)
The following each work fine individually:
def get_queryset(self):
qs = super(SomeObjectDataTableView, self).get_queryset()
return qs.select_related().annotate(items_count=Count('items'))
And
def get_queryset(self):
qs = super(SomeObjectDataTableView, self).get_queryset()
return qs.select_related().annotate(total_sum=Sum('anotherobject__differentobject__total'))
but if I try to do both, in either order, in the same annotate()
or chained one after the other, they both end up as the same number, which is the product of what they each should be.
If I add distinct=True
to the Count, it produces the correct value, but it still makes the Sum give an inflated value. (Again, changing the order doesn't help, and Sum doesn't take a distinct
parameter)
I've seen a couple of similar questions on SO, but most seemed to deal with multiple counts, which can be resolved using distinct=True
. There was one that had a Sum, but the solution involved using extra()
and some handcrafted SQL, which I've been so far unable to adapt to work with all the foreign key traversal I need to do (I've used SQL a bit, but I'm by no means an expert). Here's the basic setup of the relevant models, in case extra()
is the only viable solution:
- Item has a foreignkey to SomeObject
- AnotherObject has a foreignkey to DifferentObject and a foreignkey to SomeObject
If anyone has any idea how I can get around these problems and get both annotations on my queryset, it would be much appreciated.