Pedro Mariz
Pedro Mariz

Reputation: 161

Django creating a custom list_filter

I want to create a custom list_filter on AvariaAdmin, to check if env_emp is empty or not , i dont know how to do that

My MODELS

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

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

Upvotes: 0

Views: 118

Answers (2)

Vincent
Vincent

Reputation: 472

In your admin.py file, register the Avaria model with something like this:

class EmptyDateFilter(admin.SimpleListFilter):
    title = _('empty date')
    parameter_name = 'env_emp'

    def lookups(self, request, model_admin):
        return (
            ('all', 'All'),
            ('has_no_date', 'Has no date')
        )

    def queryset(self, request, queryset):
        value = self.value()
        if value == 'all':
           return queryset
        isnull = (value == "has_no_date")
        return queryset.filter(AvariaObjects__env_emp__isnull=isnull)

@admin.register(Avaria)
class AvariaAdmin(admin.ModelAdmin):
    list_filter = (EmptyDateFilter, )

You can find more information on the list_filter documentation

Upvotes: 1

Bernhard Vallant
Bernhard Vallant

Reputation: 50776

You can use the isnull field lookup to check if a nullable field is empty:

Pavimentacao.objects.filter(env_emp__isnull=True)

Upvotes: 0

Related Questions