I have a challenge in my project. I am using Django-Filter to generate report from my model, It works very fine using one Model and I can get all my report using the filter generated.
But when I tried to include the related table to pick some fields from the second table, I got the error Meta.fields must not contain non-model field names:
I used a sample codes I got online
Model.py
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
order_date = models.DateField()
total_price = models.DecimalField(max_digits=10, decimal_places=2)
Filter.py
import django_filters
class OrderFilter(django_filters.FilterSet):
customer_name = django_filters.CharFilter(field_name='customer__name', lookup_expr='icontains')
class Meta:
model = Order
fields = ['customer_name', 'order_date']
This is stated on the documentation of the filterset.
Note that it is not necessary to include declared filters in a fields list - doing so will only affect the order in which fields appear on a FilterSet’s form. Including declarative aliases in a fields dict will raise an error.
So the correct declarion would be:
import django_filters
class OrderFilter(django_filters.FilterSet):
customer_name = django_filters.CharFilter(field_name='customer__name', lookup_expr='icontains')
class Meta:
model = Order
fields = ['order_date'] # customer_name not included on fields