AltSchool / dynamic-rest

Dynamic extensions for Django REST Framework
MIT License
831 stars 109 forks source link

Request: supporting filter syntax that doesn't collide with f-strings #362

Open jamesbraza opened 9 months ago

jamesbraza commented 9 months ago

Currently, filter syntax directly overlaps with f-string syntax. This make string building URLs a little more cumbersome:

import httpx

def get_user_from_substring(sub_name: str):
    # I would like to use f-string in URL, but this collides with filter syntax
    response = httpx.get(f"/users/?filter{name.icontains}={sub_name}")
    ...

def get_user_from_substring(sub_name: str):
    # Workaround 1: use `__add__`
    response = httpx.get("/users/?filter{name.icontains}=" + sub_name)
    # Workaround 2: use double curly
    response = httpx.get(f"/users/?filter{{name.icontains}}={sub_name}")
    # Workaround 3: use string concatenation (black autoformats this to Workaround 2)
    response = httpx.get(
        "/users/?filter{name.icontains}=" f"{sub_name}"
    )

    ...

Can we support an alternate syntax for filter strings, so one can avoid the workarounds? Perhaps []

suavesav commented 6 months ago

Hi @jamesbraza, why would you like to avoid workaround #2?

jamesbraza commented 6 months ago

Thanks for asking for clarification. I wrote it in the original post, but to restate more concisely, it's to avoid overlap with f-strings:

# Here is an f-string and filter syntax collision, which will lead to a bug
httpx.get(f"/users/?filter{name.icontains}={sub_name}")
# Here is a workaround (requires knowing about the possible collision) to avoid the bug
httpx.get(f"/users/?filter{{name.icontains}}={sub_name}")
# What I am asking for (or something like this): configurability to avoid f-string syntax collision
httpx.get(f"/users/?filter[name.icontains]={sub_name}")