Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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()
@eddpascoal

This comment has been minimized.

Copy link

@eddpascoal eddpascoal commented Apr 10, 2015

This works? I tried but it doesn't seem to work.. Sorry for the previous comments..

@shangxiao

This comment has been minimized.

Copy link

@shangxiao shangxiao commented Sep 1, 2015

So 2 queries are run instead of one? Also, the ordering won't be guaranteed to be the same as the raw query.

@aroraumang

This comment has been minimized.

Copy link

@aroraumang aroraumang commented Dec 14, 2015

Thanks man. Working fine for me 👍

@carlosfvieira

This comment has been minimized.

Copy link

@carlosfvieira carlosfvieira commented Sep 1, 2016

this just filters the current queryset, with the ids from the raw query... does not create a new queryset, with data from raw query...

@bmuhia

This comment has been minimized.

@Odelya

This comment has been minimized.

Copy link

@Odelya Odelya commented Mar 16, 2017

Doesn't work for me as well.

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