Opened 19 months ago

Last modified 19 months ago

#34378 closed Bug

Using in_bulk() with id_list and order_by() — at Initial Version

Reported by: Ekaterina Vakhrusheva Owned by: nobody
Component: Database layer (models, ORM) Version: 4.1
Severity: Normal Keywords: ib_bulk
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

If you call in_bulk() together with the order_by(“field_1”, “field_2”).distinct(“field_1”) and specifying field_name=“field_1”, then when the result is received, the sorting order of the elements passed to order_by() is preserved. Code example:

locations = (
    UserLocation.objects.order_by("user_id", "-date_create")
    .distinct("user_id")
    .in_bulk(field_name="user_id")
)
print(locations)

>>>{2693: <UserLocation: 2023-03-01 15:17>}

However, if you specify an additional id_list argument in the in_bulk method, the sorting specified earlier in the request disappears, and as a result, another instance of the model is returned. Code example:

locations = (
    UserLocation.objects.order_by("user_id", "-date_create")
    .distinct("user_id")
    .in_bulk([2693], field_name="user_id")
)
print(locations)

>>>{2693: <UserLocation: 2023-03-01 14:27>}

A user with id 2693 has several locations that differ in the date_create. The most recent is with a time of 15:17. When sorting queryset by “-date_create” I want to get the most recent record. Therefore, the sorting is reset when passing the id_list parameter.

In my opinion, the sorting from queryset was removed before it was possible to pass different field_name to the in_bulk() method. Apparently, it was not taken into account that when sorting is reset, the result obtained when using DISTINCT changes.

https://forum.djangoproject.com/t/using-in-bulk/19192

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top