Last active
March 25, 2022 12:21
-
-
Save carymrobbins/8477219 to your computer and use it in GitHub Desktop.
Django - convert RawQuerySet to QuerySet
This file contains hidden or 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(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() |
So 2 queries are run instead of one? Also, the ordering won't be guaranteed to be the same as the raw query.
Thanks man. Working fine for me 👍
this just filters the current queryset, with the ids from the raw query... does not create a new queryset, with data from raw query...
Doesn't work for me as well.
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
This works? I tried but it doesn't seem to work.. Sorry for the previous comments..