8000 Don't raise 500 errors when filter query parameter matches a model property name. · Issue #7608 · encode/django-rest-framework · GitHub
[go: up one dir, main page]

Skip to content
Don't raise 500 errors when filter query parameter matches a model property name. #7608
Closed
@omerfarukabaci

Description

@omerfarukabaci

Checklist

  • I have verified that that issue exists against the master branch of Django REST framework.
  • I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
  • This is not a usage question. (Those should be directed to the discussion group instead.)
  • This cannot be dealt with as a third party library. (We prefer new functionality to be in the form of third party libraries where possible.)
  • I have reduced the issue to the simplest possible case.
  • I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)

Steps to reproduce

Create the following:

models.py

class OrderingFilterModel(models.Model):
    title = models.CharField(max_length=20, verbose_name='verbose title')
    text = models.CharField(max_length=100)

    @property
    def description(self):
        return self.title + ": " + self.text

serializers.py

class OrderingFilterSerializerWithModelProperty(serializers.ModelSerializer):
    class Meta:
        model = OrderingFilterModel
        fields = (
            "id",
            "title",
            "text",
            "description"
        )

views.py

class OrderingListView(generics.ListAPIView):
    queryset = OrderingFilterModel.objects.all()
    serializer_class = OrderingFilterSerializerWithModelProperty
    filter_backends = (filters.OrderingFilter,)
    ordering = ('title',)

test.py

from rest_framework.test import APIRequestFactory

factory = APIRequestFactory()

view = OrderingListView.as_view()
request = factory.get('/', {'ordering': 'description'})

Expected behavior

Ignoring the description field since it is not a model field.

Actual behavior

It is trying to use order_by on the queryset using description field, which results in the following error and return a 500 InternalServerError :

FieldError
Cannot resolve keyword 'description' into field. Choices are: id, title, text

Description

First, thanks for creating/maintaining this great library! I have opened a PR which includes both a failing test and a solution. I would be glad to discuss about the problem and the solution.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0