Search code examples
djangodjango-admindjango-admin-filters

Django admin list filter calculated field based on two fields


I have a django model shown here.

class Allocation(models.Model):
    allocated = models.IntegerField(default=5)
    used = models.IntegerField(default=0)
    user = models.ForeignKey(to=User, on_delete=models.CASCADE)

I use a calculated field as follows.

def limit_exceeded(self, obj):
        return obj.allocated == obj.used

I want to use the same logic to use it on the list_filter. But SimpleListFilter only allows one parameter_name and no way to use both fields to check the condition. How can I achieve this?


Solution

  • Something like this should probably work,

    from django.db.models import F
    
    
    class SomeFilterName(admin.SimpleListFilter):
        title = "any name"
        parameter_name = "any_name"
    
        def lookups(self, request, model_admin):
            return [("True", True), ("False", False)]
    
        def queryset(self, request, queryset):
            if self.value() == "True":
                return queryset.filter(allocated=F("used"))
            elif self.value() == "False":
                return queryset.exclude(allocated=F("used"))
            return queryset