0

I am trying to return a queryset in Django to create a list for a view with it. Having the entries for a model indexed with id's from 1 to n (the id's correlate with creation datetimes, but let's not rely on this too much), my goal is to display the first entry as first in the resultant list, but order the rest of the list reversely -- from the most recent, i.e. with the highest id number to the lowest (so id=2 should be the last one). For now I have something like this:

class ModelLC(generics.ListCreateAPIView):
  queryset = Model.objects.filter(id=1)
  aux_queryset = Model.objects.exclude(id=1).order_by('-created')
  queryset = queryset | aux_queryset

  serializer_class = ModelSerializer

  def perform_create(self, serializer):
    serializer.save(owner=self.request.user)


(id is the index column and created is the datetime field with creation timestamp.)
Upon joining the queries together the result inherits the sorting order and no matter how I rewrite it, the query, when it is actually executed, looks the same and the result is sorted by creation time in reverse order, which makes the id's also go from highest to lowest. Is it at all possible to force the query result to be "glued together" in such a weird way, but at the same time

Krzysiek Setlak
  • 311
  • 1
  • 4
  • 16

1 Answers1

1

When you concatenate a queryset with the | operator, the ORM will make one query out of it. That's why it will always sort by created DESC.

As you are using DRF, you can't use chain(), but it looks like there is a hacky way to solve it using extra()

queryset = Model.objects.extra({'is_first': 'id=1' }).order_by('-is_first', '-created')

See https://stackoverflow.com/a/30685813/7933618

masterfloda
  • 2,908
  • 1
  • 16
  • 27