gpt4 book ai didi

django - 在 admin.py 中测试自定义过滤器

转载 作者:行者123 更新时间:2023-12-03 15:12:36 24 4
gpt4 key购买 nike

我的 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__参数。是否可以测试此过滤器功能?

最佳答案

感谢 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'...

关于django - 在 admin.py 中测试自定义过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16751325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com