How To Use Db Functions In Tortoise Orm
I am trying to write a simple query but using PSQL functions CURRENT_DATE and INTERVAL, for instance: users = await User.filter(created_at__gt='CURRENT_DATE - INTERVAL '30 DAYS'')
Solution 1:
Unfortunately, Tortoise ORM processes different queries differently. For instance:
- for
updatequery you can use just a string value:
await User.filter(id=user_id).update(updated_at="now()")
- for
filterqueries you can usepypika.functionsandpypika.termsFor instance:
from pypika.terms import Parameter, Interval
await User.filter(created_at__gte=Parameter("CURRENT_DATE") - Interval(days=30))
- for
createqueries it's very tricky. Tortoise ORM is not built for that and what you need to do is to make your own field type class by inheriting fromtortoise.fields.data.DateFieldortortoise.fields.data.DateTimeFieldand overrideto_db_valuemethod.
Long story short, it is possible but very tricky, especially if you want to use all 3 types of queries: CREATE, UPDATE and SELECT.
Post a Comment for "How To Use Db Functions In Tortoise Orm"