I want to construct a value dynamically with variable number of parents python django

I am working on a django project. I have my Providable model and a foreign key: category (providable_categtory). each category can have multiple sub-categories and a providable will finally be assigned to a leaf node. here is how the category code for each providable is created:

@property
def get_code(self):
    return f"{self.category.get_code}-{self.code}"

the get_code method in providable_category:

@property
def get_code(self):
    if not self.parent:
        return self.code
    else:
        return f"{self.parent.get_code}-{self.code or self.pk_code}"

as you can see when i display a providable code in the django admin it's something like: a-b-c-6 where a,b and c are categories and 6 is the providable's own code.

so now I want to be able to search for a providable in django admin using it's full code but since the full providable code is not a field of providable it can't be done directly by adding the get_code method to search field.

what I did was, I implemented an override of the get-search_results method in my ProvidableAdmin class as below:

def get_search_results(self, request, queryset, search_term):
    # annotation for the service_code.
    queryset = queryset.annotate(
        service_code=Concat(
            "category__parent__parent__code",
            Value("-"),
            "category__parent__code",
            Value("-"),
            "category__code",
            Value("-"),
            "code"
        )
    )
    queryset, may_have_duplicates = super().get_search_results(request, queryset, search_term)
    return queryset, may_have_duplicates

and added service_code to search_fields.

this works well as long as providables have 3 parent categories. but my providable categories can have multiple parents.how can I implement a search for that? I assume I have to construct the service_code for each entry dynamically, but how can I acheive that?

Back to Top