Откат транзакции базы данных Django в цикле
Пользователь может импортировать файл excel, и я хочу проверить правильность данных.
# Excel Data
| id | item | qty |
|:---- |:------:| -----:|
| 1 | item A | 10 |
| 2 | item B | 20 |
| 3 | item C | 30 |
| 4 | item D | 40 | <-- For example, Not enough qty to minus (only have 1)
| 5 | item E | 50 |
# Database
| id | item | qty |
|:---- |:------:| -----:|
| 1 | item A | 100 |
| 2 | item B | 200 |
| 3 | item C | 300 |
| 4 | item D | 1 | <-- For example, Not enough qty to minus (Need 40)
| 5 | item E | 500 |
Мне нужно проверить в базе данных, есть ли у товара qty в минус, если да, то сохранить изменения, если нет, то откатить все измененные данные в этом excel (откатить до импорта этого excel) и вернуть данные об ошибках пользователю.
def myFunction(self, request):
try:
error_details = []
with transaction.atomic():
for data in excal_data:
result = checkIfVerify(data) # Here will be a function which will cause error 'You can't execute queries until the end of the 'atomic' block'
if result is True:
serializer = modelSerailizer(data)
serializer.save()
else:
error_details.append("some explanation...")
if len(error_details) > 0:
transaction.set_rollback(True)
raise CustomError
excpet CustomError:
pass
return Response(....)
# checkIfVerify(data)
def checkIfVerify(data):
# this sql will need to join many tables which is hard to use ORM
sql = ....
results = []
with connection.cursor() as cursor:
cursor.execute(sql)
results = cursor.fetchall()
cursor.close()
connection.close()
if results .....:
return True
else:
return False
Но проблема в том, что я не могу использовать raw SQL execute внутри блока transaction.atomic(), Если я помещаю transaction.atomic() внутрь цикла после функции проверки, он не может откатить все данные. Как мне поступить. Спасибо