[Answered ]-Django get raw query result as objects

1👍

Hm, I don’t understand why the first example works. It shouldn’t – cursor.fetchall() always returns list of tuples.

But if you want to get the list of dicts instead of tuples then use the recipe from the django documentation:

def dictfetchall(cursor):
    desc = cursor.description
    return [dict(zip([col[0] for col in desc], row))
              for row in cursor.fetchall()]
...
cursor.execute(raw_query)
invoices = dictfetchall(cursor)

1👍

To fetch raw results as model instances, use the raw() queryset method:

raw_query = "SELECT * FROM ticket WHERE customer_code = '%s'"
tickets = Ticket.objects.raw(raw_query, params=[customer.custid])

Always (yes, always) pass your parameters with the params parameter, this will protect you against SQL injection attacks. You should do the same when passing parameters to cursor.execute.

👤knbk

Leave a comment