carltongibson / django-filter

A generic system for filtering Django QuerySets based on user selections
https://django-filter.readthedocs.io/en/main/
Other
4.42k stars 767 forks source link

Add custom filter field which is not model field #1536

Closed 0xSullivan closed 1 year ago

0xSullivan commented 1 year ago

Hey I was using an old version of django-filter and I added some non-model fields for filtering. for example for user I added a name filter with custom method which concats first_name and last_name and filter both of them but there is no name field in the User model. After I updated to the latest version I faced this error:

TypeError: 'Meta.fields' must not contain non-model field names: name

I checked the codes and I found out this error happen here. in the comment it say warn if the field doesn't exist. but it actually raise a TypeError in line 349

I think it's better to make it a REAL warning instead a ERROR

carltongibson commented 1 year ago

Can you provide a minimal reproduce please, as it's not possible to see what's going on from the information given so far.

gone commented 1 year ago

A sample filter/model that replicates this:

class Profile(models.Model):
    location = models.CharField(_("location"), max_length=30)
    organization = models.CharField(_("organization"), max_length=30)
    title = models.CharField(_("title"), max_length=30)

class ProfileFilter(django_filters.FilterSet):
    search = django_filters.CharFilter(label="search", method="search")

    def search(self, queryset, name, value):
        return queryset

    class Meta:
        model = Profile
        fields = ("location", "organization", "title", "search")

The intent here would be that search isn't attached directly to the model, but appears in the fields list.

gone commented 1 year ago

Ug duplicate name error. Just name your filter something different than your method.