I have a table with scheduled and past payments, and I need to find if there are any two charges made in the same week for the same user/contract.
select count(*
If you need this only for DAY
s (which are default intervals), then simply restating your SQL as:
c2.due_time > ADDDATE(c1.due_time, - 7)
can be written in SA terms as:
filter(Charge.due_time > func.ADDDATE(OldCharge.due_time, -7))
If you need to filter for different interval types (weeks, months, years), you probably need to write a custom SQL Construct compiler (see Custom SQL Constructs and Compilation Extension for more info).
So, I ended up writing a custom date_diff() expression:
class date_diff(expression.FunctionElement):
type = Integer()
name = 'age'
@compiles(date_diff, 'default')
def _default_date_diff(element, compiler, **kw): # pragma: no cover
return "DATEDIFF(%s, %s)" % (compiler.process(element.clauses.clauses[0]),
compiler.process(element.clauses.clauses[1]),
)
@compiles(date_diff, 'mysql')
def _my_date_diff(element, compiler, **kw): # pragma: no cover
return "DATEDIFF(%s, %s)" % (compiler.process(element.clauses.clauses[0]),
compiler.process(element.clauses.clauses[1]),
)
@compiles(date_diff, 'sqlite')
def _sl_date_diff(element, compiler, **kw): # pragma: no cover
return "julianday(%s) - julianday(%s)" % (compiler.process(element.clauses.clauses[0]),
compiler.process(element.clauses.clauses[1]),
)