Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a queryset's current order_by ordering

I'd like to find adjacent items in a queryset given a primary key, as asked here. However I want this to work for any given queryset, that i haven't set the ordering for myself. How can I find the current ordering of a queryset for __gt and __lt filtering?

For example:

queryset = MyModel.objects.all().order_by('some_field')
next_obj = get_next(queryset, after_pk, 10)
...
def get_next(queryset, pk, n):
    #ordering is unknown here
    obj = queryset.get(pk=pk)
    field = queryset.get_order_by_field_name() #???
    return queryset.filter(**{field+'__gt': getattr(obj, field)})[:n]

The model may define a default ordering and I can check if the queryset is ordered, but I don't think either are helpful in this case.

like image 562
jozxyqk Avatar asked Aug 21 '15 12:08

jozxyqk


1 Answers

You can retrieve the list of columns from order_by clause by accessing queryset.query.order_by property.

From django docs:

The query attribute is an opaque object. It represents the internals of the query construction and is not part of the public API. However, it is safe (and fully supported) to pickle and unpickle the attribute’s contents as described here.

like image 105
Akisame Avatar answered Oct 26 '22 02:10

Akisame