Ticket #6641: 6641-get_or_create.diff

File 6641-get_or_create.diff, 1.2 KB (added by Timothée Peignier <tim@…>, 12 years ago)

Catch IntegrityError

  • django/db/models/query.py

     
    11from django.conf import settings
    2 from django.db import connection, transaction
     2from django.db import connection, transaction, IntegrityError
    33from django.db.models.fields import DateField, FieldDoesNotExist
    44from django.db.models import signals, loading
    55from django.dispatch import dispatcher
     
    285285        try:
    286286            return self.get(**kwargs), False
    287287        except self.model.DoesNotExist:
    288             params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
    289             params.update(defaults)
    290             obj = self.model(**params)
    291             obj.save()
    292             return obj, True
     288            try:
     289                params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
     290                params.update(defaults)
     291                obj = self.model(**params)
     292                obj.save()
     293                return obj, True
     294            except IntegrityError, e:
     295                return self.get(**kwargs), False
    293296
    294297    def latest(self, field_name=None):
    295298        """
Back to Top