Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Modified get_or_create(), to *reduce* the chance of IntegrityError exceptions, and raises ObjectNotReady when the collision is detected.
- cal.leeming [at] simplicitymedialtd.co.uk
- """
- from django.db import models
- from django.db import IntegrityError
- from django.db import DatabaseError
- class ObjectNotReady(Exception):
- pass
- class ExtendedManager( models.Manager ):
- # 28th april 2011:
- # please note, it is best to use UNSIGNED INTEGERS, else you will get very VERY
- # strange problems with it saying there is a duplicate key when there isn't lol.
- # reason being, if you put in an integer above the maximum signed INT, django
- # auto down converts it, which is fucking retarded. and the lookup afterwards in
- # this logic, does things properly.. so it ends up failing.
- # see ticket: http://code.djangoproject.com/ticket/15923
- def get_or_create(self, *args, **kwargs):
- created = None
- try:
- return super(ExtendedManager, self).get_or_create(*args, **kwargs)
- except IntegrityError, e:
- # Ensure the error code matches 1062 (duplicate entry)
- if not e.args[0] == 1062:
- raise e
- try:
- _obj = self.get(**kwargs)
- except self.model.DoesNotExist:
- res = self.filter(**kwargs).all()
- if res.count() == 1:
- _obj = res[0]
- else:
- raise ObjectNotReady, "Object busy or not yet ready: %s" % ( e )
- return (_obj, False)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement