Невозможно выполнить запросы при вставке многосвязных объектов в файле миграции Django
Я хочу инициировать основные данные 4 связанных моделей в файл миграции. Вот список моих моделей:
Test
QuestionCategory(with `Test` FK)
Question(with `QuestionCategory` and `Test` FK)
А также вот моя функция, которая импортирует данные в файл миграции:
def step3(apps, db_alias):
import pandas as pd
import os
file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'initial_data/PyTest-BasicData.xlsx')
questions_df = pd.read_excel(file_path, sheet_name='Questions', engine='openpyxl', )
questions_list = questions_df.T.to_dict().values()
QuestionCategory = apps.get_model("PsyTest", "QuestionCategory")
Question = apps.get_model("PsyTest", "Question")
for item in questions_list:
category_title = None if pd.isna(item["category_title"]) else item["category_title"]
category_type_choice = None if pd.isna(item["category_type_choice"]) else item["category_type_choice"]
category_reference_title = None if pd.isna(item["category_reference_title"]) else item["category_reference_title"]
reference = None
int_test_pk =int(item["test_pk"])
if category_reference_title:
try:
reference = QuestionCategory.objects.using(db_alias).get(test_id=int_test_pk, title=category_reference_title)
except QuestionCategory.DoesNotExist:
reference = QuestionCategory(test_id=int_test_pk, title=category_reference_title, category=1)
reference.save()
try:
category = QuestionCategory.objects.using(db_alias).get(test_id=int_test_pk, title=category_title)
except QuestionCategory.DoesNotExist:
category = QuestionCategory(test_id=int_test_pk, title=category_title, category=int(category_type_choice),
reference=reference)
category.save()
try:
_ = Question.objects.using(db_alias).get(test_id=int_test_pk, title=item["title"])
except Question.DoesNotExist:
question = Question(test_id=int_test_pk, title=item["title"], row=int(item["row"]),
is_active=item["is_active"], category=category)
question.save()
В другой функции я импортировал Test объектов в файл миграции и все идет хорошо, Но когда я использую несколько моделей и отношений в файле миграции - как в вышеуказанной функции - я получил эту ошибку:
raise TransactionManagementError(
django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.
Как я могу решить эту проблему?