I\'m trying to use django\'s queryset API to emulate the following query:
SELECT EXTRACT(year FROM chosen_date) AS year,
EXTRACT(month FROM chosen_date) AS
Would this work?:
from django.db import connection, transaction
cursor = connection.cursor()
sql = """
SELECT
%s AS year,
%s AS month,
date_paid IS NOT NULL as is_paid
FROM (
SELECT
(CASE WHEN date_due IS NULL THEN date_due ELSE date END) AS chosen_date, *
FROM
invoice_invoice
) as t1;
""" % (connection.ops.date_extract_sql('year', 'chosen_date'),
connection.ops.date_extract_sql('month', 'chosen_date'))
# Data retrieval operation - no commit required
cursor.execute(sql)
rows = cursor.fetchall()
I think it's pretty save both CASE WHEN and IS NOT NULL are pretty db agnostic, at least I assume they are, since they are used in django test in raw format..