Мне нужно вставить несколько объектов в таблицу. Есть два способа сделать это:
1) Вставьте каждый из них, используя
Код: Выделить всё
save()2) Insert all of them together using
Код: Выделить всё
bulk_create()Clearly, second option is better and hence I am using that. Now the problem with
Код: Выделить всё
bulk__createTo overcome this, we need to fetch the objects created by
Код: Выделить всё
bulk_createNow the question is "assuming as in my situation, there is no way to uniquely identify the created objects, how do we fetch them?"
Currently I am maintaining a time_stamp to fetch them, something like below-
Код: Выделить всё
my_objects = []
# Timestamp to be used for fetching created objects
time_stamp = datetime.datetime.now()
# Creating list of intantiated objects
for obj_data in obj_data_list:
my_objects.append(MyModel(**obj_data))
# Bulk inserting the instantiated objects to dB
MyModel.objects.bulk_create(my_objects)
# Using timestamp to fetch the created objects
MyModel.objects.filter(created_at__gte=time_stamp)
- If at the time of bulk-creating these objects, some more objects are created from somewhere else, then those objects will also be fetched in my query, which is not desired.
Источник: https://stackoverflow.com/questions/328 ... ion-of-dja