【问题标题】:Django admin search should include inline fields tooDjango 管理员搜索也应该包括内联字段
【发布时间】:2017-08-14 02:51:18
【问题描述】:

我正在尝试在模型管理员 search_fields 中包含一个内联字段,但我无法弄清楚。

from django.contrib import admin
from yourapp.models import Supplier, Product

class ProductInline(admin.TabularInline):
    model = Product

class SupplierAdmin(admin.ModelAdmin):
    inlines = [ProductInline,]


admin.site.register(Supplier, SupplierAdmin)

这里我想在 SupplierAdmin 类中搜索产品,虽然产品是内联的,但我无法获得搜索功能

【问题讨论】:

    标签: javascript python django python-2.7


    【解决方案1】:

    您需要创建自定义过滤器对象并将其传递给 Admin 类的 list_filters 属性。详情请参考documentation

    基本上你需要的是一个过滤器,比如:

    class ProductFilter(admin.SimpleListFilter):
       # Human-readable title which will be displayed in the
       # right admin sidebar just above the filter options.
       title = 'Filter title'
       # Parameter for the filter that will be used in the URL query.
       parameter_name = 'name_of_parameter'
    
       def queryset(self, request, queryset):
          """
          Returns the filtered queryset based on the value
          provided in the query string and retrievable via
          `self.value()`.
          """
          # Compare the requested value (either '80s' or 'other')
          # to decide how to filter the queryset.
          if self.value():
             return queryset.filter(product_FIELD_YOU_WANT_TO_FILTER=self.value())
          else:
             return queryset
    
    class SupplierAdmin(admin.ModelAdmin):
       inlines = [ProductInline,]
       list_filter = (ProductFilter,)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-27
      • 2014-10-15
      • 1970-01-01
      • 2011-05-10
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多