DJANGO,自定义LIST_FILTER

问题描述 投票:0回答:2

我只使用django管理员,并尝试创建自定义过滤器,其中是过滤另一个模型的日期。

我的模特

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 = ('')
django django-admin django-filter
2个回答
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)

0
投票

您必须添加要过滤的字段。在你的例子中,如果你想过滤日期,你就把list_filter('date')。别忘了注册模型管理员,如here

© www.soinside.com 2019 - 2024. All rights reserved.