django - convert a list back to a queryset

PythonDjangoListSortingDjango Queryset

Python Problem Overview


I have a handful of records that I would like to sort based on a computed value. Got the answer over here... like so:

sorted(Profile.objects.all(), key=lambda p: p.reputation)

on a Profile class like this:

class Profile(models.Model):
    
    ...
    
    @property
    def reputation(self):
        ...

Unfortunately the generic view is expecting a queryset object and throws an error if I give it a list.

Is there a way to do this that returns a queryset

or...

Can I convert a list to a queryset somehow? Couldn't find anything like that in the django docs.

I am hoping not to denormalize the data, but I guess I will if I have to.

Update / Answer:

it seems that the only way to get a queryset back is if you can get all of your logic into the sql queries.

When that is not possible, (I think) you need to denormalize the data

Python Solutions


Solution 1 - Python

Ok...this post is now old BUT what you could do is get all the ids of the objects in your list, then perform a model.objects.filter(pk__in=list_of_ids)

Solution 2 - Python

There is no point in converting a data list back to a query. A query object never holds data; it just represents a query to the database. It would have to fetch everything again if you made your list to a query, and that would be redundant and very bad performance-wise.

What you can do:

  • Describe how the reputation field is calculated; it's probably possible to order the data in the database somehow.
  • Modify the view to not require a query object. If it needs to do additional filtering etc. this should be done before any ordering, since the ordering will take less time with less entries (and less data will be fetched from the database.) So you could send the filtered query object to the sort function just before you send it to the template (which shouldn't care whether it's a query or a list.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJiaaroView Question on Stackoverflow
Solution 1 - PythonneolaserView Answer on Stackoverflow
Solution 2 - PythonBlixtView Answer on Stackoverflow