Skip to content

Instantly share code, notes, and snippets.

@gskoljarev
Forked from carymrobbins/raw_as_qs.py
Last active March 22, 2017 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gskoljarev/bb32fbb0aea2033016860a8d47bb0d2e to your computer and use it in GitHub Desktop.
Save gskoljarev/bb32fbb0aea2033016860a8d47bb0d2e to your computer and use it in GitHub Desktop.
Django - Execute a raw query and return a QuerySet
from django.db import connection, models
class MyManager(models.Manager):
def raw_as_qs(self, raw_query, params=()):
"""Execute a raw query and return a QuerySet. The first column in the
result set must be the id field for the model.
:type raw_query: str | unicode
:type params: tuple[T] | dict[str | unicode, T]
:rtype: django.db.models.query.QuerySet
"""
with connection.cursor() as c:
c.execute(raw_query, params)
return self.filter(id__in=(row[0] for row in c.fetchall()))
class MyModel(models.Model):
objects = MyManager()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment