DJANGO,自定义LIST_FILTER

时间:2019-02-19 10:29:59

标签: django django-admin django-filter

我仅使用django admin,并尝试创建一个自定义过滤器,该过滤器用于过滤另一个模型的日期。

我的模型

class Avaria(models.Model):
 .....
class Pavimentacao(models.Model):

    avaria = models.ForeignKey(Avaria, related_name='AvariaObjects',on_delete=models.CASCADE)
    date= models.DateField(blank=True,null=True)

AvariaAdmin

class AvariaAdmin(admin.ModelAdmin):
    list_filter = ('')

2 个答案:

答案 0 :(得分:1)

例如,假设您有一个模型,然后必须将自定义ContentTypeFilter添加到模型管理员。您可以定义一个继承SimpleListFilter的类,并根据需要定义lookupsqueryset,并将该类添加到list_filter中,例如

list_filter = [ContentTypeFilter]

请参阅docs

示例类定义如下:

class ContentTypeFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('content type')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'type'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        models_meta = [
            (app.model._meta, app.model.__name__) for app in get_config()
        ]
        return (item for item in models_meta)

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """

        if not self.value():
            return

        model = apps.get_model(self.value())
        if model:
            return queryset.models(model)

答案 1 :(得分:0)

您必须添加要过滤的字段。在您的示例中,如果要过滤日期,请放入list_filter('date')。别忘了像here

一样注册模型管理员