Как эффективно извлекать объекты после создания с помощью функции Bulk_create Django ORM?Python

Программы на Python
Гость
Как эффективно извлекать объекты после создания с помощью функции Bulk_create Django ORM?

Сообщение Гость »


Мне нужно вставить несколько объектов в таблицу. Есть два способа сделать это:

1) Вставьте каждый из них, используя. But in this case there will be n sql dB queries for n objects.

2) Insert all of them together using

Код: Выделить всё

bulk_create()
. In this case there will be one sql dB query for n objects.

Clearly, second option is better and hence I am using that. Now the problem with

Код: Выделить всё

bulk__create
is that it does not return ids of the inserted objects hence they can not be used further to create objects of other models which have foreign key to the created objects.

To overcome this, we need to fetch the objects created by

Код: Выделить всё

bulk_create
.

Now 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)
Now this works good, but will fail in one case.
  • 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.
Can someone come up with a better solution?


Источник: https://stackoverflow.com/questions/328 ... ion-of-dja

Вернуться в «Python»