我有模型
class Order(models.Model):
order_id = models.CharField(max_length=30, default='', unique = True)
amount = models.FloatField()
我有这个循环将对象从 json 保存到我的数据库并验证唯一字段order_id
for json_obj in json_data:
order = Order(symbol=json_obj['order_id'], amount= json_obj['amnount'])
try:
order.save()
except IntegrityError as exception:
if 'UNIQUE constraint failed' in exception.args[0]:
print('duplicate order id => skip this')
continue
一切正常,但是当我将 @transaction.atomic 装饰器添加到我的函数时,一切都会中断。我得到一个错误:
"An error occurred in the current transaction. You can't "
django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.
处理这种情况的推荐方法是什么?
UPD:我使用事务原子装饰器来加速我的代码,因为我有大量的订单要保存,而且这是一个在后台运行的相当昂贵的操作。
UPD2:我尝试使用get_or_create method 但没有得到任何真正的性能提升,所以不能使用它
慕村9548890
浮云间
相关分类