-
-
Save gskoljarev/bb32fbb0aea2033016860a8d47bb0d2e to your computer and use it in GitHub Desktop.
Django - Execute a raw query and return a QuerySet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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