How to use a property method in list_filter in custom admin changelist?

Viewed 1180

I have a model like this:

class CustomUser(AbstractUser):
    @property
    def is_paid(self):
        return self.apayment4thisuser.all().filter(expirydate__gt=timezone.now().date()).count()>0

In the customadmin I am able to add is_paid in list_display, but it is throwing error when I add it to my list_filter:

class CustomUserAdmin(UserAdmin):
    model = CustomUser
    list_filter = ['app_user','is_paid']
    list_display = ['id',
                    'username',
                    'email',
                    'is_paid',
                    ]

This is the error:

ERRORS:
<class 'users.admin.CustomUserAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'is_paid', which does not refer to a Field.

Is there not any way to add this to list_filter?

1 Answers

With a custom filter like this :

class IsPaidFilter(SimpleListFilter):

   # Human-readable title which will be displayed in the
   # right admin sidebar just above the filter options.
   title = 'is paid'

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

   def lookups(self, request, model_admin):
      return (
           ('True', True), 
           ('False', False)
             )

   def queryset(self, request, queryset): 
      if self.value():
          # If is_paid=True filter is activated
          return queryset.filter(<Write your logic here>)
      else:
          # If is_paid=True filter is activated
          return queryset.filter(<Write your other logic>)

And for this logic, this could be useful :

Q(Count(apayment4thisuser, 
      filter=Q(apayment4thisuser__expirydate__gt=timezone.now().date())))
Related