0

I'm using django-eztables to do server-side processing of a datatable. It's been working fine so far, but now I'm trying to add a field to my table that contains the total number of objects associated with the object via a particular foreign key. It's easy enough to get this to display properly on the client side using fnRender, but since sorting is done on the server side, I need to actually do the aggregation on the server side. This has been proving difficult.

I can't seem to find a way to handle this on the server side. The entries in the fields object only seem to accept actual model fields, and I don't see a way to slip in the annotation suggested by my google findings. I've looked into defining a custom sort, but since I'm just building a string, this doesn't really seem to help.

Ideally, I'd like to find a way to use an aggregation of the foreign key relationship right in the fields dictionary, something like:

fields = {
    'id': 'id',
    'name': 'name',
    'total_items': 'items__count' #Something like this, where Item has a foreign key to the object the datatable is composed of
    #More fields...
}

If that's not possible, or not feasible, just making it so that the sorting is based on the aggregation is fine, since I can change the data displayed in the table from the client side, and I don't need to do any filtering.

StephenTG
  • 2,579
  • 6
  • 26
  • 36

1 Answers1

0

I eventually realized that I could put in the annotation in when I was overriding the get_queryset, like so:

def get_queryset(self):
    qs = super(SomeObjectDataTableView, self).get_queryset()
    return qs.select_related().annotate(items_count=Count('items'))

Probably should have figured this out earlier...

StephenTG
  • 2,579
  • 6
  • 26
  • 36