5

我的admin.py文件中有以下过滤器:

class parentCategoryFilter(admin.SimpleListFilter):
    title = 'parent category'
    parameter_name = 'parent_category'

    def lookups(self, request, model_admin):
        first_level_categories = model_admin.get_queryset(request).filter(parent_category__isnull=True)

        if first_level_categories:

            lookups = (('none', 'None'),)

            for first_level_category in first_level_categories:
                lookups += ((first_level_category.id, first_level_category.name),)

            return lookups

    def queryset(self, request, queryset):
        if self.value() == 'none':
            return queryset.filter(parent_category__isnull=True)
        elif self.value():
            try:
                return queryset.filter(parent_category=int(self.value()))
            except (ValueError, TypeError):
                return queryset.none()
        else:
            pass

我想在我的tests.py文件中对其进行测试,但是在尝试实例化该类时,它开始询问我大约 5 个__init__参数。是否可以测试此过滤器功能?

4

2 回答 2

14

感谢 karthikr 和大量阅读,我想出了以下解决方案(使用 Django 的 Pool 示例):

过滤方法定义如下:

class WasPublishedRecentlyFilter(admin.SimpleListFilter):
    title = 'Was published recently'
    parameter_name = 'published_recently'

    def lookups(self, request, model_admin):
        return (
            ('yes', 'Yes',),
            ('no', 'No',),
        )

    def queryset(self, request, queryset):
        if self.value() == 'yes':
            #filter logic
        elif self.value() == 'no':
            #filter logic
        elif self.value():
            return queryset.none() 

以及过滤器的测试:

def test_filter(self):
    Poll.objects.create(question='Sup?', pub_date=timezone.now())
    Poll.objects.create(question='How you doing?', pub_date=timezone.now() - datetime.timedelta(days=1))

    filter = admin.WasPublishedRecentlyFilter(None, {'published_recently':'yes'}, Poll, admin.PollAdmin)
    poll = filter.queryset(None, Poll.objects.all())[0]
    self.assertEqual(poll.question, 'Sup?')

    filter = admin.WasPublishedRecentlyFilter(None, {'published_recently':'no'}, Poll, admin.PollAdmin)
    poll = filter.queryset(None, Poll.objects.all())[0]
    self.assertEqual(poll.question, 'How you doing?')

和输出:

Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 0.124s

OK
Destroying test database for alias 'default'...
于 2013-05-27T15:48:45.960 回答
6

需要的5个参数__init__来自admin.SimpleListFilter__init__定义为:(Source

def __init__(self, request, params, model, model_admin):

您可以传入这些参数来测试您的过滤器

于 2013-05-25T19:12:14.553 回答