django-ajax-datatable
django-ajax-datatable copied to clipboard
Problem with choices/autofilter when query contains annotate
Hi, first of all, congratulations on this amazing extension!
I have a problem with the choices option and the use of the custom query. I'm using an annotate function to add a field to the main model, and the “choices” option works on the fields of the main model but not on the field of the table that uses a join.
Here is my views.py:
class PatchListView(AjaxDatatableView):
model = Patch
title = 'Patchs'
initial_order = [
["datacenter_name", "asc"],
["patch_region", "asc"],
]
length_menu = [[20, 50, 100, -1], [20, 50, 100, 'all']]
def datacenter_id(self, value):
return int(value['datacenter_id'])
def get_initial_queryset(self, request=None):
datacenter_id = int(self.kwargs['datacenter_id'])
queryset = (
Patch.objects.all()
.annotate(datacenter_name=F("patch_dc_name_id__datacenter_name"))
)
if datacenter_id: queryset = queryset.filter(patch_dc_name_id=datacenter_id)
return queryset
def get_column_defs(self, request=None):
datacenter_id = int(self.kwargs['datacenter_id'])
return [
{
'name': 'datacenter_name',
'visible': False if datacenter_id else True,
'title': 'Datacenter',
'choices': True,
'autofilter': True
},
{'name': 'patch_region', 'title': 'Region', 'choices': True, 'autofilter': True},
{'name': 'patch_instance', 'title': 'EC2 Name', 'choices': True, 'autofilter': True},
{'name': 'patch_name', 'title': 'Package Name'},
{'name': 'patch_date', 'title': 'Package Installation'},
]
No problem with patch_region and patch_instance fields, but it doesn't works with datacenter_name
Thanks a lot for your help!
Ok I understood my mistake, it was enough to use foreign_field, now it works.
I can't wait for the xls/csv export function to be implemented ;-)