Django-filter order_by "Cannot resolve keyword 'name' on field"

Using django-filter, I have the following FilterSet:

class MyFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(name='full_name')

    class Meta:
        model = MyModel
        fields = ['name',]
        order_by_field = 'order'
        order_by = ('name',)

      

As you can see, I named the field full_name

, so it filters the full_name

table column . But as soon as I installed order_by

in name

, it gave me this error:

Unable to resolve keyword 'name' on field. The following options are possible: ...

It filters with help ?name=Jon%20Doe

, but the order doesn't work. What could be the problem?

+3


source to share


1 answer


In the Meta.order_by documentation, you need to use the field name from the model, not the filter field name. In your case, I would just use full_name

which is on the model:

class MyFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(name='full_name')

    class Meta:
        model = MyModel
        fields = ['name',]
        order_by_field = 'order'
        order_by = ('full_name',)

      



If you look at the code: https://github.com/alex/django-filter/blob/develop/django_filters/filterset.py#L326-L339 you can see that if you declared an order_by field it will go through the form fields (generated from the model), then uses that value as the order_by argument to the QuerySet.

Anyway, the documentation should be more explicit in this fact.

+1


source







All Articles