Skip to content

Instantly share code, notes, and snippets.

@hbasria
Forked from carymrobbins/raw_as_qs.py
Created January 29, 2016 14:03
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hbasria/6c829d349918cc2923fb to your computer and use it in GitHub Desktop.
Save hbasria/6c829d349918cc2923fb to your computer and use it in GitHub Desktop.
Django - convert RawQuerySet to QuerySet
from django.db import connection, models
class MyManager(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
"""
cursor = connection.cursor()
try:
cursor.execute(raw_query, params)
return self.filter(id__in=(x[0] for x in cursor))
finally:
cursor.close()
class MyModel(models.Model):
objects = MyManager()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment