tortoise / tortoise/tortoise-orm

Use of variable with RawSQL - annotating a time delta

Open
#1,280 0 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

Hi,

Does Tortoise ORM provide a safe way to pass my_datetime in to the following query:



class Event(tortoise.models.Model):
    id = tortoise.fields.UUIDField(pk=True)
    scheduled_for = tortoise.fields.DatetimeField(index=True)


my_datetime = datetime.datetime(2022, 10, 20, 11, 30, 30, tz=zoneinfo.ZoneInfo("UTC"))


await models.Event.annotate(
    scheduled_for_delta=tortoise.functions.functions.Abs(
        tortoise.expressions.RawSQL("julianday(scheduled_for) - julianday(my_datetime)")
    )
).order_by('scheduled_for_delta')

I was wanting to get the queryset ordered by the smallest time delta of scheduled_for and my_datetime (i.e. the nearest scheduled event to the provided datetime).

Is there a better way or different approach to do this with TortoiseORM that I haven't found? I'm using sqlite.

Thanks!

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

Start with the RawSQL expression and annotate query shown in the issue, using SQLite as the target backend. Determine whether Tortoise ORM supports safely supplying my_datetime for this calculation and ordering by the absolute time delta; done means a supported approach is identified or implemented and its behavior is covered.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, sqlite
Domain
database
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.