Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/query.rst
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ The following lookup types are available:
- ``iendswith`` - case insensitive ``endswith``
- ``iexact`` - case insensitive equals
- ``search`` - full text search
- ``date`` - date search on datetime field e.g.; `await Team.filter(created_at__date=datetime.date(2020, 5, 20))`

For PostgreSQL and MySQL, the following date related lookup types are available:

Expand Down
9 changes: 9 additions & 0 deletions tests/test_filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,15 @@ async def test_filter_not_with_or(self):
self.assertEqual(len(tournaments), 2)
self.assertSetEqual({t.name for t in tournaments}, {"0", "1"})

async def test_filter_date(self):
await DatetimeFields.create(
datetime=datetime.datetime(
year=2020, month=5, day=20, hour=0, minute=0, second=0, microsecond=0
)
)
date = datetime.date(2020, 5, 20)
self.assertEqual(await DatetimeFields.filter(datetime__date=date).count(), 1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should have more tests for these: checking that this filter modifier actually converts a date time to a date. The provided test case doesn't actually test anything. For instance, in Postgres

SELECT TIMESTAMP '2024-01-20 00:00:00' = DATE '2024-01-20';
> true


@test.requireCapability(dialect="mysql")
@test.requireCapability(dialect="postgres")
async def test_filter_exact(self):
Expand Down
11 changes: 10 additions & 1 deletion tortoise/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from pypika_tortoise import SqlContext, Table
from pypika_tortoise.enums import DatePart, Matching, SqlTypes
from pypika_tortoise.functions import Cast, Extract, Upper
from pypika_tortoise.functions import Cast, Date, Extract, Upper
from pypika_tortoise.terms import (
BasicCriterion,
Criterion,
Expand Down Expand Up @@ -185,6 +185,10 @@ def insensitive_ends_with(field: Term, value: str) -> Criterion:
)


def date_equal(field: Term, value: str) -> Criterion:
return Date(field).eq(value)


def extract_year_equal(field: Term, value: int) -> Criterion:
return Extract(DatePart.year, field).eq(value)

Expand Down Expand Up @@ -523,6 +527,11 @@ def get_filters_for_field(
"operator": insensitive_posix_regex,
"value_encoder": string_encoder,
},
f"{field_name}__date": {
"field": actual_field_name,
"source_field": source_field,
"operator": date_equal,
},
f"{field_name}__year": {
"field": actual_field_name,
"source_field": source_field,
Expand Down