Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

python - 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'")

How to make it work? Thanks

question from:https://stackoverflow.com/questions/65951082/how-to-use-db-functions-in-tortoise-orm

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately, Tortoise ORM processes different queries differently. For instance:

  • for update query you can use just a string value:
await User.filter(id=user_id).update(updated_at="now()")
  • for filter queries you can use pypika.functions and pypika.terms For instance:
from pypika.terms import Parameter, Interval

await User.filter(created_at__gte=Parameter("CURRENT_DATE") - Interval(days=30))
  • for create queries 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 from tortoise.fields.data.DateField or tortoise.fields.data.DateTimeField and override to_db_value method.

Long story short, it is possible but very tricky, especially if you want to use all 3 types of queries: CREATE, UPDATE and SELECT.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...