我的目标是对最后修改的查询集进行排序。我搜索了一个解决方案,并找到了“ xmin”属性(1)。我找不到如何访问此“伪”列的信息,这使我不得不考虑使用原始SQL从查询集中“注释”每个xmin,因为以下SQL起作用了:
SELECT xmin, * FROM media ORDER BY xmin::text::bigint;
我的尝试是以下三个:
将原始SQL应用于查询集 我知道做错了,因为SQL不仅适用于当前查询集,而且适用于整个表:
mediaQS = Media.objects.filter(id__in=mediaIDList)
for media in mediaQS.annotate(xmin=RawSQL("SELECT xmin FROM media ;")):
print "media.xmin",media.xmin`
哪个会引发TypeError:__init __()至少接受3个参数(给定2个参数)
我的第二次和第三次尝试均基于this issue(Django 2.1)
for media in mediaQS.extra(select={'my_xmin': 'xmin'}):
print "media.my_xmin",media.my_xmin
哪个给
django.db.utils.ProgrammingError: column "xmin" does not exist
LINE 1: SELECT (xmin) AS "my_xmin", "media"."id", "media"."path_id",...
^
HINT: There is a column named "xmin" in table "media", but it cannot be referenced from this part of the query.
和
from django.db.models import Expression
class XMin(Expression):
output_field = models.PositiveIntegerField()
def as_postgresql(self, compiler, connection):
return 'xmin', ()
for media in mediaQS.annotate(my_xmin=XMin()):
print "media.my_xmin",media.my_xmin
哪个给出类似的错误:
django.db.utils.ProgrammingError: column "xmin" does not exist
LINE 1: ..."path" AS "media_path", T4."path" AS "thumbnail", xmin AS "m...
^
HINT: There is a column named "xmin" in table "media", but it cannot be referenced from this part of the query.
如果有人可以为Django 1.11解决方案提供帮助,我表示感谢。