tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

date part filter not working

Open cesar-nascimento opened this issue 3 years ago • 2 comments

when you have a field type of fields.DateField or fields.DatetimeField and you need to query by date part as exemplified in:

class DatePart(Enum):
    year = "YEAR"
    quarter = "QUARTER"
    month = "MONTH"
    week = "WEEK"
    day = "DAY"
    hour = "HOUR"
    minute = "MINUTE"
    second = "SECOND"
    microsecond = "MICROSECOND"

teams = await Team.filter(created_at__year=2020)
teams = await Team.filter(created_at__month=12)
teams = await Team.filter(created_at__day=5)

It will return the following error when you try to execute the query iso8601.iso8601.ParseError: expected string or bytes-like object.

I'm currently running the code inside a docker container using python:3.10-alpine3.16, and postgres:14.4-alpine3.16 and the tortoise_orm version 0.19.2.

however, if you pass a string instead with the format YYYY-MM-DD it will return the following error instead: tortoise.exceptions.OperationalError: invalid input syntax for type numeric: "2022-08-09" and the database will output the following ERROR: invalid input syntax for type numeric: "2022-08-09"

this is what I'm currently doing to "fix" the error:

class DateFieldNoParsing(fields.DateField):
    def to_db_value(self, value: int, instance: "Union[Type[Model], Model]"):
        self.validate(value)
        return value

cesar-nascimento avatar Aug 09 '22 01:08 cesar-nascimento

Can you print the raw sql?

long2ice avatar Aug 25 '22 03:08 long2ice

this is the error log from the Docker container: ERROR: invalid input syntax for type numeric: "2022-08-25" at character 156

STATEMENT: SELECT "id","usuario_id","descricao","data","valor" FROM "receita" WHERE UPPER(CAST("descricao" AS VARCHAR))=UPPER('string') AND EXTRACT(YEAR FROM "data")='2022-08-25' AND EXTRACT(MONTH FROM "data")='2022-08-25' AND "usuario_id"='7f8b1a6a-324a-49a1-b279-d1e4aa705b97' LIMIT 1

this is the command I'm using:

item.filter(
    descricao__iexact=item.descricao,
    data__year=str(item.data),
    data__month=str(item.data),
    usuario_id=user.id,
).first()

cesar-nascimento avatar Aug 25 '22 16:08 cesar-nascimento