Django in_bulk() 使用 distinct() 引发错误

Django in_bulk() raising error with distinct()

我有以下查询集:

MyModel.objects
.order_by("foreign_key_id")
.distinct("foreign_key_id")
.in_bulk(field_name="foreign_key_id")

foreign_key_idMyModel 上不是唯一的,但鉴于 distinct 的使用在 QuerySet 中应该是唯一的。

然而,当它运行时会出现以下错误:

"ValueError: in_bulk()'s field_name must be a unique field but 'foreign_key_id' isn't."

根据 in_bulk here it should be possible to use in_bulk with distinct in this way. The ability was added to Django in response to this issue ticket here 上的 Django 文档。

我需要在此处更改什么才能使这项工作正常进行?

我正在使用 Django3.1 和 Postgres11。

正如 documentation of in_bulk(…) 所说:

(…)

Changed in Django 3.2:

Using a distinct field was allowed.

由于您使用 , this will thus not work, you will thus have to upgrade your program to .