Sort added elements inside Django autocomplete_fields

965 Views Asked by At

I have Django application and admin page.

Inside admin page, I have one model that has autocomplete_fields. I can sort results but, I can't sort the results.

enter image description here

It always sort by pk and not by value that I set.

@admin.register(Assortment)
class AssortmentAdmin(ImportExportActionModelAdmin):

    list_display = ['name']
    exclude = ['customers']
    # inlines = [ProductAssortmentInLine]
    autocomplete_fields = ['products']



@admin.register(Product)
class ProductAdmin(ImportExportActionModelAdmin):
    exclude = ['associated_products', 'subsidiary_excluded', 'customers']
    list_display = ['product_ref', 'name', 'price', 'group', 'retail_unit', 'active']
    list_editable = ['price', 'retail_unit', 'active']
    list_filter = ['group']
    search_fields = ['product_ref', 'name', 'group']
    resource_class = ProductResource
    # inlines = [CustomerInLine]

    def get_queryset(self, request):
        qs = super(ProductAdmin, self).get_queryset(request)
        qs = qs.order_by(Cast(F('product_ref'), IntegerField()))
        return qs

How to solve this?

1

There are 1 best solutions below

0
On

According to the django docs the ordering for autocomplete fields is set by the get_ordering method of the Product Admin not get_queryset. Hope this helps but not sure how you would integrate the complex query that you have into it.

https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields