strawberry-graphql / strawberry-django

Strawberry GraphQL Django extension
https://strawberry.rocks/docs/django
MIT License
415 stars 120 forks source link

Feature Request: Filters with custom names #125

Closed hiporox closed 7 months ago

hiporox commented 2 years ago

Feature Request Type

Description

Filters currently require the Django relationship to be present in the name of the filter. For example, if you want to filter on a field called created_at, the filter name must be created_at. The proposal here to untie the name of the filter from the name in the database. So you could have the database field be named created_at, but the GraphQL filter be called created.

Where this feature would be most useful is in hiding many to many through relationships that you want to filter on. For example, if you want to provide a filter on task__assignments__assignee that will filter a task down to which user it is currently assigned to. In an ideal world, the TaskFilter would have an assignee field that you could filter on, even though that direct database relation does not exist.

The current work around for this is to define a filter_assignee method on the task filter, that then applies this filtering to the queryset. The issue is that filter methods are not nestable. If you have a project with multiple tasks, and you want to find all projects with a task that is assigned to a particularly user, it would be most natural to write the following query:

query projectsAssignedToUser($userId: ID) {
  projects(filters: { tasks: { assignee: { id: { exact: $userId } } } }) {
    ...
  }
}

Because nested method filters do not work, this filter syntax does not work.

Proposed API

I suggest we change the filter API definition to allow an optional value that can take override arguments for things like this. You would define a task filter like this:

@strawberry_django.filters.filter(Task)
class TaskFilter:
  id: FilterLookup[strawberry.id]
  assignee: UserFilter = strawberry_django.filters.filter_field(lookup="assignments__assginee")

Upvote & Fund

Fund with Polar

bellini666 commented 2 years ago

Hi @hiporox ,

I like this idea! Would you like to try to implement it and open a PR for us?

bellini666 commented 7 months ago

https://github.com/strawberry-graphql/strawberry-django/pull/478