如何在Tortoise ORM中使用db函数 [英] How to use db functions in Tortoise ORM

查看:366
本文介绍了如何在Tortoise ORM中使用db函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个简单的查询,但是使用PSQL函数CURRENT_DATE和INTERVAL,例如:

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

如何使其工作?谢谢

推荐答案

不幸的是,Tortoise ORM对不同查询的处理方式不同.例如:

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

  • 对于 update 查询,您可以仅使用一个字符串值:
  • for update query you can use just a string value:
await User.filter(id=user_id).update(updated_at="now()")

  • 对于 filter 查询,您可以使用 pypika.functions pypika.terms 例如:
    • 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))
      

      • 用于 create 查询非常棘手.Tortoise ORM不是为此而构建的,您需要做的是通过继承 tortoise.fields.data.DateField tortoise.fields.data.DateTimeField 并覆盖 to_db_value 方法.
        • 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.
        • 长话短说,这是可能的,但非常棘手,特别是如果您要使用所有三种查询类型:CREATE,UPDATE和SELECT.

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

          这篇关于如何在Tortoise ORM中使用db函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆