Last active
April 15, 2021 06:46
-
-
Save poppingtonic/792cd601ff9cc4605882865cfb48e1ac to your computer and use it in GitHub Desktop.
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
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() |
This should be simpler. I'll edit it
'generator' object has no attribute 'items' in obj_ranks.items()
python3.5 django 1.11
from myapp.models import Mymodel
Mymodel.objects.filter(pk__in=[i.pk for i in Mymodel.objects.raw("SELECT * FROM mytable")])
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.
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
qs is the queryset you'd like to call the
.raw
SQL query on