Sam R.
Sam R.

Reputation: 16450

django-filter order_by "Cannot resolve keyword 'name' into 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 have named the field to full_name so it filters on the full_name column of table. But once I set the order_by to name it gives me this error:

Cannot resolve keyword 'name' into field. Choices are: ...

It filters with ?name=Jon%20Doe but the ordering doesn't work. What could be the problem?

Upvotes: 3

Views: 1713

Answers (1)

Michael B
Michael B

Reputation: 5388

Per the documentation on Meta.order_by, you have to use a field name from the model, not a 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 have a look at the code: https://github.com/alex/django-filter/blob/develop/django_filters/filterset.py#L326-L339, you will see that if you have declared an order_by field, it loops through the form fields (generated from the model), then uses that value as an argument to order_by on the QuerySet.

If anything, the documentation should be more explicit on this fact.

Upvotes: 2

Related Questions