TransactionManagementError “You can't execute queries until the end of the 'atomic' block” while using signals, but only during Unit Testing

后端 未结 11 2096
有刺的猬
有刺的猬 2020-12-02 06:03

I am getting TransactionManagementError when trying to save a Django User model instance and in its post_save signal, I\'m saving some models that have the user as the forei

11条回答
  •  醉话见心
    2020-12-02 06:23

    I was getting this error on running unit tests in my create_test_data function using django 1.9.7. It worked in earlier versions of django.

    It looked like this:

    cls.localauth,_ = Organisation.objects.get_or_create(organisation_type=cls.orgtypeLA, name='LA for test', email_general='test@test.com', address='test', postcode='test', telephone='test')
    cls.chamber,_ = Organisation.objects.get_or_create(organisation_type=cls.orgtypeC, name='chamber for test', email_general='test@test.com', address='test', postcode='test', telephone='test')
    cls.lawfirm,_ = Organisation.objects.get_or_create(organisation_type=cls.orgtypeL, name='lawfirm for test', email_general='test@test.com', address='test', postcode='test', telephone='test')
    
    cls.chamber.active = True
    cls.chamber.save()
    
    cls.localauth.active = True
    cls.localauth.save()    <---- error here
    
    cls.lawfirm.active = True
    cls.lawfirm.save()
    

    My solution was to use update_or_create instead:

    cls.localauth,_ = Organisation.objects.update_or_create(organisation_type=cls.orgtypeLA, name='LA for test', email_general='test@test.com', address='test', postcode='test', telephone='test', defaults={'active': True})
    cls.chamber,_ = Organisation.objects.update_or_create(organisation_type=cls.orgtypeC, name='chamber for test', email_general='test@test.com', address='test', postcode='test', telephone='test', defaults={'active': True})
    cls.lawfirm,_ = Organisation.objects.update_or_create(organisation_type=cls.orgtypeL, name='lawfirm for test', email_general='test@test.com', address='test', postcode='test', telephone='test', defaults={'active': True})
    

提交回复
热议问题