Advertisement
Guest User

Cal Leeming [Simplicity Media Ltd]

a guest
May 9th, 2011
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. """Modified get_or_create(), to *reduce* the chance of IntegrityError exceptions, and raises ObjectNotReady when the collision is detected.
  2.  
  3. cal.leeming [at] simplicitymedialtd.co.uk
  4. """
  5.  
  6. from django.db import models
  7.  
  8. from django.db import IntegrityError
  9. from django.db import DatabaseError
  10.  
  11. class ObjectNotReady(Exception):
  12.     pass
  13.  
  14. class ExtendedManager( models.Manager ):
  15.     # 28th april 2011:
  16.     # please note, it is best to use UNSIGNED INTEGERS, else you will get very VERY
  17.     # strange problems with it saying there is a duplicate key when there isn't lol.
  18.     # reason being, if you put in an integer above the maximum signed INT, django
  19.     # auto down converts it, which is fucking retarded. and the lookup afterwards in
  20.     # this logic, does things properly.. so it ends up failing.
  21.     # see ticket: http://code.djangoproject.com/ticket/15923
  22.    
  23.     def get_or_create(self, *args, **kwargs):
  24.         created = None
  25.         try:
  26.             return super(ExtendedManager, self).get_or_create(*args, **kwargs)
  27.  
  28.         except IntegrityError, e:
  29.             # Ensure the error code matches 1062 (duplicate entry)
  30.             if not e.args[0] == 1062:
  31.                 raise e
  32.  
  33.             try:
  34.                 _obj = self.get(**kwargs)
  35.             except self.model.DoesNotExist:
  36.                 res = self.filter(**kwargs).all()
  37.                 if res.count() == 1:
  38.                     _obj = res[0]
  39.  
  40.                 else:
  41.                     raise ObjectNotReady, "Object busy or not yet ready: %s" % ( e )
  42.  
  43.             return (_obj, False)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement