[Django]-Use non model django fields in django filter

4👍

This may not be the most performant solution, but I was able to get it working.

Step 1: Read the Django Filter docs.

https://django-filter.readthedocs.io/en/stable/index.html

Step 2: Add a property to your Django model named cptCodeTBX.

from django.db import models

class MyModel(models.Model):
    field = models.CharField(max_length=60)

    @property
    def cptCodeTBX(self):
        """
        Does all the code tbx cpt stuff, can do whatever you want.
        """

        cptCodeTBX = 2323 #whatever value you want     
        return cptCodeTBX

Step 3: Add a Django Filter.

import django_filters    

class CptCodeTBXFilter(django_filters.FilterSet):
    """
    Filter that will do all the magic, value comes from url query params.
    Replace filters.NumberFilter with any filter you want like
    filters.RangeFilter.
    """

    cptCodeTBX = django_filters.NumberFilter(
        field_name="cptCodeTBX",
        method="filter_cptCodeTBX",
        label="Cpt Code TBX",
    )

    def filter_cptCodeTBX(self, queryset, name, value):
        objects_ids = [
            obj.pk for obj in MyModel.objects.all() if obj.cptCodeTBX == value
        ]
        if objects_ids:
            queryset = MyModel.objects.filter(pk__in=objects_ids)
        else:
            queryset = MyModel.objects.none()
        return queryset

Step 4: Pass the value through the url as a query parameter.

http://example.com/?cptCodeTBX=00622

Leave a comment