morlandi / django-ajax-datatable

A Django app which provides the integration of a Django project with the jQuery Javascript library DataTables.net
MIT License
211 stars 64 forks source link

Problem with choices/autofilter when query contains annotate #132

Open carruno opened 1 week ago

carruno commented 1 week ago

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!

carruno commented 1 week ago

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 ;-)