Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Could JSON Fields support filter like 'in' 'gt' 'lt' ? #1082

Closed
CherishW0316 opened this issue Mar 8, 2022 · 1 comment · Fixed by #1789
Closed

Could JSON Fields support filter like 'in' 'gt' 'lt' ? #1082

CherishW0316 opened this issue Mar 8, 2022 · 1 comment · Fixed by #1789

Comments

@CherishW0316
Copy link

Now JSON Fields filter only support contanins, contained__by, could support filter like 'in' 'gt' 'lt' and more operations?

@BigGitHubLaLaLa
Copy link

BigGitHubLaLaLa commented May 11, 2022

from tortoise.contrib.mysql.json_functions import operator_keywords 
from tortoise.filters import between_and,is_in,Like
from pypika.terms import Term,BasicCriterion

class In(BasicCriterion):  
    def __init__(self, left, right, alias=None) -> None:
        super().__init__(" IN ", left, right, alias=alias)

    def get_sql(self, quote_char='"', with_alias=False, **kwargs):
        sql = "{left}{comparator}{right}".format(
            comparator=self.comparator,
            left=self.left.get_sql(quote_char=quote_char, **kwargs),
            right=self.right.get_sql(quote_char=quote_char, **kwargs),
        )

        return sql

def _mysql_json_in(left: Term, value: tuple):
    return In(left,left.wrap_constant(value))

def _mysql_json_between(left: Term, value: list):
    return between_and(left,value)

def _mysql_json_like(left: Term, value: str):
    return Like(left, left.wrap_constant(f"%{value}%"),escape="")



operator_keywords["between"] = _mysql_json_between
operator_keywords["like"] = _mysql_json_like
operator_keywords["in"] = _mysql_json_in
await Model.filter(json_filed__filter={"field__in":(1,2,3)})
await Model.filter(json_filed__filter={"field__like":"1"})
await Model.filter(json_filed__filter={"field__between":(1,2)})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants