Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@poppingtonic
Last active April 15, 2021 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poppingtonic/792cd601ff9cc4605882865cfb48e1ac to your computer and use it in GitHub Desktop.
Save poppingtonic/792cd601ff9cc4605882865cfb48e1ac to your computer and use it in GitHub Desktop.
import operator
from functools import reduce
results = qs.model.objects.raw(sql, sql_params)
obj_ranks = (obj.id for obj in results)
return_objs = []
# inject rank
for obj_id, objs.items():
return_objs.append(qs.filter(id=obj_id))
if len(return_objs) > 0:
qs = reduce(operator.or_, return_objs)
else:
qs = qs.model.objects.none()
@poppingtonic
Copy link
Author

qs is the queryset you'd like to call the .raw SQL query on

@poppingtonic
Copy link
Author

This should be simpler. I'll edit it

@sergiomb2
Copy link

sergiomb2 commented Jul 11, 2017

'generator' object has no attribute 'items' in obj_ranks.items()

python3.5 django 1.11

@DiegoMagg
Copy link

DiegoMagg commented Oct 29, 2020

from myapp.models import Mymodel

Mymodel.objects.filter(pk__in=[i.pk for i in Mymodel.objects.raw("SELECT * FROM mytable")])

@JackAtOmenApps
Copy link

JackAtOmenApps commented Nov 16, 2020

from myapp.models import Mymodel

Mymodel.objects.filter(pk__in=[i.pk for i in Mymodel.objects.raw("SELECT * FROM mytable")])

@DiegoMagg, while yours is likely more efficient, it loses the main benefit of the gist: To keep the new QuerySet if the same ordering as the RawQuerySet.

If order doesn't matter, then yours is the better alternative, but if you set a specific ordering in the raw query, then the gist's approach (or something like it) is the way to go.

@lewisMachilika
Copy link

Mymodel.objects.filter(pk__in=[i.pk for i in Mymodel.objects.raw("SELECT * FROM mytable")])

This does not work for me
return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: ('The SQL contains 11409 parameter markers, but 76945 parameters were supplied', 'HY000')

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