используя метод свойства в list_filter в пользовательском администраторе - PullRequest
0 голосов
/ 05 апреля 2020

У меня есть такая модель:

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

в customadmin. Я могу добавить это под моим списком отображения, но выдает ошибку, когда я добавляю его в свой фильтр списка:

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

Это ошибка:

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

Мне было интересно, нет ли способа добавить это в list_filter?

Спасибо,

1 Ответ

0 голосов
/ 05 апреля 2020

С таким фильтром:

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>)

И для этой логики c это может быть полезно:

Q(Count(apayment4thisuser, 
      filter=Q(apayment4thisuser__expirydate__gt=timezone.now().date())))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...