0

我有 Django 应用程序和管理页面。

在管理页面内,我有一个模型具有autocomplete_fields. 我可以对结果进行排序,但是我无法对结果进行排序。

在此处输入图像描述

它总是按 pk 而不是我设置的值排序。

@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

如何解决这个问题?

4

1 回答 1

0

根据 django 文档,自动完成字段的排序由 Product Admin 的get_ordering方法设置,而不是get_queryset。希望这会有所帮助,但不确定如何将您拥有的复杂查询集成到其中。

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

于 2021-01-27T20:22:10.537 回答