vitalik / django-ninja

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs
https://django-ninja.dev
MIT License
6.59k stars 395 forks source link

How to implement a generic Filter #1199

Open eugenenelou opened 2 weeks ago

eugenenelou commented 2 weeks ago

I want to implement a generic filter that will allow me to filter by multiple possible values.

for example query fruits of a certain type with: /fruits?type=apple,banana,plum

this is the implementation that almost works, the only problem is that I would have to pass q="type__in" and this would not be generic. I think that a q_suffix (I don't care about the name) would permit to make this generic by making the name of the field implicit.

from typing import Annotated, TypeVar

from pydantic import BaseModel, Field, BeforeValidator

T = TypeVar("T")

InFilter = Annotated[
    list[T], BeforeValidator(lambda v: v.split(",")), Field(q_suffix="__in")
]

class Filters(FilterSchema):
  type: InFilter[str]

So did I miss something and is that already possible?

eugenenelou commented 1 week ago

I opened a PR for this https://github.com/vitalik/django-ninja/pull/1212

instead of adding q_suffix, I just allowed the field name to be implicit, which is a lot lighter.