1

Written a filter that is functioning as it should

class ExternalProductActiveStatusFilter(admin.SimpleListFilter):

    title = "EP Active status"
    parameter_name = "ep active status"

    def lookups(self, request, model_admin):
        return [
            ("active", "Active"),
            ("inactive", "Inactive"),
        ]

    def queryset(self, request, queryset):
        if self.value() == "active":
            return queryset.distinct().filter(external_products__active=True)
        if self.value() == "inactive":
            return queryset.exclude(external_products__active=True)

Now I want to test it but can't get it to work.

Looked into old SO questions but the solutions do not do the trick. These ones in particular, Test a custom filter in admin.py(7 years old) and Django filter testing(5 years old)

My test as of right now

    def test_externalproductactivestatusfilter_active(self):
        self.product1 = baker.make(
            "products.Product", id=uuid4(), title="Active product"
        )
        self.product2 = baker.make(
            "products.Product", id=uuid4(), title="Inactive product"
        )

        self.external_product1 = baker.make(
            "external_products.ExternalProduct",
            internal_product=self.product1,
            active=True,
        )
        self.external_product2 = baker.make(
            "external_products.ExternalProduct",
            internal_product=self.product2,
            active=False,
        )

        request = MockRequest()

        f = ExternalProductActiveStatusFilter(
            None, {"active": "Active"}, Product, ProductAdmin
        )
        result = f.queryset(request, Product.objects.all())

        print(result)

result is None

1 Answers1

0

Of corse None: You have two return in if, and nothing else. IF filter not set - you receive None. In your case:

def queryset(self, request, queryset):
    query = Q()
    if self.value() == "active":
        query = Q(external_products__active=True)
    if self.value() == "inactive":
        query = Q(external_products__active=False)
    return queryset.filter(query)
Maxim Danilov
  • 2,472
  • 1
  • 3
  • 8
  • I see. Now I don't get None, but the filter isn't "executing" in the test, I get both products. Do you know how to rewrite the test to get it to work? – Jonas Fagerlund Sep 04 '22 at 20:11