Skip to content

Instantly share code, notes, and snippets.

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

This comment has been minimized.

Copy link

@Odelya Odelya commented Mar 16, 2017

What is qs?

@poppingtonic

This comment has been minimized.

Copy link
Owner Author

@poppingtonic poppingtonic commented May 17, 2017

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

@poppingtonic

This comment has been minimized.

Copy link
Owner Author

@poppingtonic poppingtonic commented May 17, 2017

This should be simpler. I'll edit it

@sergiomb2

This comment has been minimized.

Copy link

@sergiomb2 sergiomb2 commented Jul 11, 2017

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

python3.5 django 1.11

@DiegoMagg

This comment has been minimized.

Copy link

@DiegoMagg 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")])
@OmenApps

This comment has been minimized.

Copy link

@OmenApps OmenApps 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

This comment has been minimized.

Copy link

@lewisMachilika lewisMachilika commented Apr 15, 2021

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