gpt4 book ai didi

django - 通过排序获取查询集的当前order_

转载 作者:行者123 更新时间:2023-12-04 14:11:13 26 4
gpt4 key购买 nike

我想在给定主键的查询集中找到相邻项,如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,并且我可以检查queryset是否为 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.

关于django - 通过排序获取查询集的当前order_,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32140362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com