使用日期字段以外的字段类型的 latest() 方法 (Django)

Usage of latest() method with field types other than date field (Django)

我刚刚了解了 latest() 方法。我去了 django 的文档以了解更多相关信息。在文档中写道:

latest(field_name=None)

Returns the latest object in the table, by date, using the field_name provided as the date field.

但是在我遵循的教程中,此方法与 models.PositiveIntegerField() 字段的字段名称一起使用(并且模型未指定 get_latest_by)。我一直在尝试搜索此方法的解释和类似用法,其中 field_name 与日期字段不同。

我找到了一些信息here,其中是这样说的:

...it probably does work with other total-ordered types too, but not sure...

It does work with primary keys ...

我也发现了类似的情况 here,其中 latest() 方法与 id 字段一起使用。

但是我仍然没有找到答案是否可以将此方法用于日期字段以外的其他内容?还有其他方法更适合这种任务吗?

Here's the source code for _earliest_or_latest, which powers the latest method. As you can see, it basically uses whatever field name you specify and tries its best to order your lookup by that field at the database level. It does this through the add_ordering method, which is documented in the source code here.

引擎盖下并没有什么特别的东西 - Django 只是传递一个 ORDER BY 并让数据库尝试解决问题。这就是为什么您会看到数据库环境之间行为不一致的原因,例如 SQLite 如何将空值排序在非空值之下,而 MySQL 和 PostgreSQL 则相反。 Django 并没有真正对查询集进行排序,它是底层数据库。

诸如日期、递增 ID 等内容对于数据库来说很容易排序,因此与 latest 配合得很好。另一方面,UUIDField 可能效果不佳。