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
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']
CodePudding user response:
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’smanufacturer__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.