Django 过滤器测试

标签 django python-3.x django-testing django-filter

class BusinessPartnerFilter(SilBaseFilter):
    active = django_filters.BooleanFilter(
        name='date_deactivated', lookup_expr='isnull')
    parent_name = django_filters.CharFilter(name='parent__name')
    unmapped = django_filters.BooleanFilter(method='check_if_unmapped')

我添加了字段 'unmapped'上面并创建了方法 filter以下。有人可以帮我写过滤器的测试吗?我被困住了。
class Meta(object):
    model = models.BusinessPartner
    fields = [
        'name', 'bp_type', 'slade_code', 'parent', 'national_identifier',
        'active', 'parent_name', 'unmapped'
    ]

    def check_if_unmapped(self, queryset, field, value):
        if value:
            exclude_bps = [record.id for record in queryset if record.mapped == 0 and record.unmapped == 0]
            return queryset.exclude(id__in=exclude_bps)
        return queryset

最佳答案

您可以单独测试过滤器方法,也可以测试 FilterSet.qs 的评估.

要测试过滤器方法,您不一定需要完全初始化的 FilterSet .

qs = BusinessPartner.objects.all()
f = BusinessPartnerFilter()
result = f.check_if_unmapped(qs, 'unmapped', True)
# assert something about the result

也就是说,完全初始化 FilterSet 并不困难。并检查 .qs .

qs = BusinessPartner.objects.all()
f = BusinessPartnerFilter(data={'unmapped': 'True'}, queryset=qs)
result = f.qs
# assert something about the result

关于Django 过滤器测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45756602/

相关文章:

python - 在 Django 中通过 URL 传递静态字符串参数(模型选择)?

django - South 处理模型 mixin 吗?

python - 将日期时间序列化为 JSON

python - 如何使用 MongoDB 在 Django 中的 request.user 中设置 User

javascript - django CSS : general query on CDNs and crispy forms

python - 安装gobject模块?

Python 列表表示法,Numpy 数组表示法 : predictions[predictions < 1e-10] = 1e-10

django - 在 Django 中模拟模型方法

python - 将 24 小时制转换为 12 小时制

django - 在 Django context_processor 中测试 request.resolver_match