How can I get computed elements of a table in a django queryset?

后端 未结 5 1528
野的像风
野的像风 2021-01-17 20:53

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          


        
5条回答
  •  悲哀的现实
    2021-01-17 21:12

    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..

提交回复
热议问题