在事务中使用时,Cursor'对象没有属性'_last_executed'

时间:2015-12-05 11:35:39

标签: mysql django transactions

我在MySQL Db中创建了一些条目。

class Images(models.Model):
    isactive = models.BooleanField(_('Active Flag'), default=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

这些图像可以与模型类Bike相关联。

现在我创建了很多自行车,并尝试在事务中执行此操作,以便创建所有对象或不创建任何对象。

    @transaction.atomic
    def create_in_db(**kwargs):
        try:
            bike = Bike(**bikedata)
            bike.save()
            create_others(data)  
            #create some other related models(If they fail I don't want Bike as well)
            create_images(bikeimages, bike)
        except Exception as e:
            #log errors
            raise e

def create_images(images, related_to_obj):
    for image in images.values():
        try:
            image['content_object'] = related_to_obj
            image['user'] = user
            i = Image(**image)
            i.save()
        except Exception as e:
            #log errors 
            pass  

如果图像在调用i.save()时已经存在于db中,它会抛出Integrity Error,我会抓住它。跳过一些图像不是问题。但在我得到Integrity error剩下的i.save()投掷Cursor' object has no attribute '_last_executed'之后,既没有创建图像也没有创建自行车。

如果我删除@transaction.atomic行,一切正常,并且不会创建抛出Intergrity Error的图像,其余图像与Bike对象关联并持久保存到数据库。

0 个答案:

没有答案