tortoise / tortoise-orm

Familiar asyncio ORM for python, built with relations in mind
https://tortoise.github.io
Apache License 2.0
4.57k stars 376 forks source link

Support string queries #972

Open clayscode opened 2 years ago

clayscode commented 2 years ago

Is your feature request related to a problem? Please describe. It would be nice for Tortoise ORM to support string queries to make it easier to implement search functionality in web applications

Describe the solution you'd like Something like ModelName.fiter("name__icontains: 'Bill' age__gt: '32'")

Basically it would be the same as the Query functionality, but as a string.

long2ice commented 2 years ago

What about RawSQL?

BobDotCom commented 2 years ago

If you don't want to use RawSQL, maybe you could make yourself a helper function for it, something like this.

from ast import literal_eval
from typing import Any

def calculate(value: str) -> dict[str, Any]:
    sects = value.split(",")
    values = {}
    for sect in sects:
        key, raw = sect.split('=')
        values[key.strip()] = literal_eval(raw.strip())  # Safe eval
    return values

calculate("name__icontains='Bill', age__gt='32'")  # {'name__icontains': 'Bill', 'age__gt': '32'}`

These could then be passed in as kwargs to the filter method via ModelName.filter(**calculate("name__icontains='Bill', age__gt='32'"))