Opened 3 years ago

Closed 3 years ago

#32323 closed Bug (duplicate)

Lazy object id fetch on object initialization.

Reported by: Bartłomiej Nowak Owned by: nobody
Component: Database layer (models, ORM) Version: 2.2
Severity: Normal Keywords: bulk_create, fetch id, lazy id fetch, can_return_ids_from_bulk_insert
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Let's assume I am using the Postgres database, so the flag can_return_ids_from_bulk_insert is True.

I would like to do this:

class ModelA:
      pass

class ModelB:
      a = models.ForeginKey(ModelA)

a_to_create = []
b_to_create = []
for _ in some_data:
    a = ModelA(...)
    a_to_create.append(a)
    b_to_create.append(
          ModelB(a=a, ...)
     )

ModelA.objects.bulk_create(a_to_create)
# all objects in the a_to_create list have now ids, becouse of can_return_ids_from_bulk_insert flag. a_to_create[0].id will return int. 
ModelA.objects.bulk_create(b_to_create)

But when I initialize ModelB(a=a), Django immediately fetches id from object a, which is None in this line, and using this latter, instead of fetching it (id) from the provided object, when it's going to create. Why do not fetch this id lazy?

Because of this situation, I have to do an additional loop for every additional model.

Thank you

Change History (1)

comment:1 by Mariusz Felisiak, 3 years ago

Resolution: duplicate
Status: newclosed
Type: New featureBug
Note: See TracTickets for help on using tickets.
Back to Top