tortoise / tortoise/tortoise-orm

date part filter not working

Open
#1,217 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.6k
Forks
516
Avg merge
2d 21h
Merged PRs (30d)
9

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the DateField and DatetimeField date-part filters shown in the issue with PostgreSQL, including the integer and YYYY-MM-DD inputs. Start from the DateField to_db_value path and the Team.filter calls; done means year, month, and day lookups execute without parsing or numeric-type errors and return the matching teams.

Written by the indexing model from the issue text.

Assessment

Tech stack
postgresql, python
Domain
database
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.