获取查询集的当前 order_by 顺序

Get a queryset's current order_by ordering

我想按照要求在给定主键的情况下查找查询集中的相邻项 here。但是我希望这适用于任何给定的查询集,我还没有为自己设置顺序。如何找到 __gt__lt 过滤的查询集的当前排序?

例如:

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]

该模型可能会定义一个默认值 ordering and I can check if the queryset is ordered,但我认为在这种情况下两者都没有用。

您可以通过访问 queryset.query.order_by 属性.

从 order_by 子句中检索列列表

来自 django 文档:

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.