Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tools to ease executing raw SQL with Django ORM

Tags:

python

orm

django

I often need to execute custom sql queries in django, and manually converting query results into objects every time is kinda painful. I wonder how fellow Slackers deal with this. Maybe someone had written some kind of a library to help dealing with custom SQL in Django?

like image 214
Сыч Avatar asked Sep 26 '26 05:09

Сыч


1 Answers

Not exactly sure what you're looking for, but you can always add a method onto a model to execute custom SQL per the docs:

def my_custom_sql(self):
  from django.db import connection
  cursor = connection.cursor()
  cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
  row = cursor.fetchone()
  return row

For something more generic, create an abstract base model that defines a function like that with an "sql" parameter.

like image 102
Dave Avatar answered Sep 28 '26 22:09

Dave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!