Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

3 django model filterset with django-filter

I have 3 different django models and I want to filter using django-filter.
The ORM query I wrote below works without any problems. but how can i do this with django-filter (filters.FilterSet) ?

Employee.objects.filter(companyrecord__company__cname__icontains="ompanyname") THIS IS WORKS

it is work for me in ORM. But how can i do this in filter set. I wrote above what I want to do

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My Models:

class Employee(models.Model):
    employee_name = models.CharField(...)

class CompanyRecord(models.Model):
    employee = models.ForeignKey(Employee)
    company = models.ForeignKey(Company)

class Company(models.Model):
    cname = models.CharField(...)

My FilterSet:

class EmployeeFilter(filters.FilterSet):
    full_name = filters.CharFilter(field_name="full_name", lookup_expr='icontains')

    class Meta:
        model = Employee
         fields = ['full_name']

>Solution :

The field_name=… parameter [readthedocs.io] can accept a chain of field names, like when you filter. Indeed:

Field names can traverse relationships by joining the related parts with the ORM lookup separator (__). e.g., a product’s manufacturer__name.

So you can work with:

class EmployeeFilter(filters.FilterSet):
    full_name = filters.CharFilter(
        field_name="full_name", lookup_expr='icontains'
    )
    company_name = filters.CharFilter(
        field_name="companyrecord__company__cname", lookup_expr='icontains'
    )

    class Meta:
        model = Employee
        fields = ['full_name']

Then you thus filter with the company_name for that filter.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading