Django admin custom filter

2020. 12. 30. 19:26파이썬/Django

class NullFilter(admin.SimpleListFilter) :
    parameter_name = 'title'
    title = 'title'

    def lookups(self, request, model_admin) :
        return (
            ('Not Null', 'Not empty only'),
            ('Null', 'Empty only'),
        )

    def queryset(self, request, queryset) :
        title= self.value()
        if title== 'Not Null' :
            return queryset.filter(category__isnull=False)
        elif title== 'Null' :
            return queryset.filter(category__isnull=True)

        return queryset

admin의 list_filter에 위 클래스 추가

    list_filter = ['aaaa','bbbb',NullFilter]

class TrainedFilter(admin.SimpleListFilter) :
    title = 'Trained'
    parameter_name = 'Trained'

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

    def queryset(self, request, queryset) :
        if self.value() == 'True' :
            for image in queryset :
                if image.isTrained() == False :
                    queryset = queryset.exclude(id=image.id)
            return queryset
        elif self.value() == 'False' :
            for image in queryset :
                if image.isTrained() == True :
                    queryset = queryset.exclude(id=image.id)
            return queryset
        
        return queryset 

'파이썬 > Django' 카테고리의 다른 글

관련 문의  (0) 2021.01.07
Django import export 참고자료  (0) 2021.01.06
migrate가 아무 작동을 하지 않는 경우  (0) 2020.12.29
python manage.py makemigrations app_label  (0) 2020.12.29
No installed app with label 'App이름'.  (0) 2020.12.29