If somebody want to know a solution in the future, that’s the way I solve it:
There is currently no way to return the IDs from a bulk create insert with any built-in Django method or function. So what I did was use the filter()
method.
I thought about filtering based on the values given by the user, but one of the most obvious flaws is that these values are not unique. However, because I store the creation date and time of each insert, it is possible to filter the most recent data by time. bulk_create()
inserts all the data in a single query, so the time will always be the same for each query, no matter how long the list of inserted values is.
# Filter objects using a DateTimeField with auto_now_add = True and storage the IDs in a list
indicators = EducationalPlanIndicators.objects.filter(created_at=indicators_inst[0].created_at).values_list('id', flat=True)
# Use a for loop to read the list and add the IDs one at the time
for idi in indicators:
if idi != ',':
query = EducationalPlanIndicators.objects.get(id=idi)
plan.indicators_id.add(query)
I don’t know is this solution isn’t efficient for huge information insertions, but I think is good enough for simple insertions, like 8-10 rows.