tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

functions annotate feature

Open mylot-python opened this issue 6 years ago • 4 comments

Excuse me, tortoise-orm have like Django's (TruncMonth /TruncQuarter/someTrunc/ExtractDay/ExtractMonth/someExtract) functions?

mylot-python avatar Jul 23 '20 02:07 mylot-python

You can build it yourself, example:

from pypika import CustomFunction
from tortoise.expressions import F
from tortoise.functions import Function

class TruncMonth(Function):
    database_func = CustomFunction("DATE_FORMAT", ["name", "dt_format"])

sql = Task.all().annotate(date=TruncMonth('created_at', '%Y-%m-%d')).values('date').sql()
print(sql)
# SELECT DATE_FORMAT(`created_at`,'%Y-%m-%d') `date` FROM `task`

All of custom function just like that.

long2ice avatar Aug 24 '20 10:08 long2ice

Hi @long2ice , I need your help,

For date_trunc (Postgresql function) the value position is on the right side not on the left side like DATE_FORMAT Mysql Function,

how I can switch or select the position of the value and field ?

Thanks. :)

Rhyanz46 avatar Jan 15 '22 16:01 Rhyanz46

@Rhyanz46 In case you're still looking for answer, you can do this:

from tortoise.expressions import Function
from pypika_tortoise import CustomFunction
from pypika_tortoise.terms import Function as PypikaFunction

# create pypika specific function
class _TruncMonth(PypikaFunction):
    def __init__(self, field_name, dt_format, alias=None):
        # switch parameter position below
        super().__init__("DATE_FORMAT", dt_format, field_name, alias=alias)

# create tortoise specific function
class TruncMonth(Function):
    database_func = _TruncMonth

bhch avatar Aug 09 '26 15:08 bhch

@Rhyanz46 In case you're still looking for answer, you can do this:

from tortoise.expressions import Function from pypika_tortoise import CustomFunction from pypika_tortoise.terms import Function as PypikaFunction

create pypika specific function

class _TruncMonth(PypikaFunction): def init(self, field_name, dt_format, alias=None): # switch parameter position below super().init("DATE_FORMAT", dt_format, field_name, alias=alias)

create tortoise specific function

class TruncMonth(Function): database_func = _TruncMonth

Thanks for the answer, I've even not touch code anymore, I let them all to the claude code bro, thanks for answer me 🤣 thanks bro 🔥

Rhyanz46 avatar Aug 09 '26 15:08 Rhyanz46