【问题标题】:Sort added elements inside Django autocomplete_fields在 Django autocomplete_fields 中对添加的元素进行排序
【发布时间】:2021-04-19 09:48:48
【问题描述】:

我有 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

如何解决?

【问题讨论】:

    标签: python django django-admin autocomplete-fields


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2011-10-29
      • 1970-01-01
      • 2012-12-26
      相关资源
      最近更新 更多