Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Last active March 25, 2022 12:21
Show Gist options
  • Save carymrobbins/8477219 to your computer and use it in GitHub Desktop.
Save carymrobbins/8477219 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()
@Odelya
Copy link

Odelya commented Mar 16, 2017

Doesn't work for me as well.

@andr0s
Copy link

andr0s commented Mar 25, 2022

This will kill the DB performance if the number of results is huge (say, hundreds of thousands and more)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment