﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
20761	UnboundLocalError: local variable 'sid' referenced before assignment when using get_or_create with a badly formed __init__	alastair.porter@…	loic84	"The cause of this bug seems to be a little convoluted. I don't expect it to happen in normal use, but it still seems to be unexpected behaviour.

The smallest testcase I can create it with is:


{{{
class Test(models.Model):
    def __init__(self, **kwargs):
        import django.db
        raise django.db.IntegrityError(""oops"")
}}}


The cause of the Integrity error isn't important. I was trying some stuff in a custom __init__ that didn't end up working. The error I get is:

{{{
In [2]: models.Test.objects.get_or_create(id=1)

/env/local/lib/python2.7/site-packages/django/db/models/manager.pyc in get_or_create(self, **kwargs)
    144 
    145     def get_or_create(self, **kwargs):
--> 146         return self.get_query_set().get_or_create(**kwargs)
    147 
    148     def create(self, **kwargs):

/env/local/lib/python2.7/site-packages/django/db/models/query.pyc in get_or_create(self, **kwargs)
    479                 return obj, True
    480             except IntegrityError as e:
--> 481                 transaction.savepoint_rollback(sid, using=self.db)
    482                 exc_info = sys.exc_info()
    483                 try:

UnboundLocalError: local variable 'sid' referenced before assignment
}}}

The reason for this seems to be that the try: block in query.py:get_or_create expects the IntegrityError to be thrown when the new object is saved, not when it's created (line 476)."	Bug	closed	Database layer (models, ORM)	dev	Normal	fixed			Accepted	1	0	0	0	0	0
