Pedro Mariz
Pedro Mariz

Reputation: 161

DJANGO , custom LIST_FILTER

I am using only the django admin , and trying to creating a custom filter, where is to filter the date of another model.

My models

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 = ('')

Upvotes: 0

Views: 2417

Answers (2)

webbyfox
webbyfox

Reputation: 1069

For example, Let's say you have a model and you have to add custom ContentTypeFilter to your model admin then. you can define a class which inherit SimpleListFilter and define lookups and queryset based on your requirement and add this class to list_filter like

list_filter = [ContentTypeFilter]

Refer to docs

Example class definition is like below:

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)

Upvotes: 1

Jonas Vandermosten
Jonas Vandermosten

Reputation: 163

You have to add the field you want to filter. In your example if you want to filter on date you put list_filter('date'). Dont forget to register the model admin as seen here

Upvotes: 0

Related Questions