Ticket #9029: 9029-get-or-create-r12805.diff

File 9029-get-or-create-r12805.diff, 1.7 KB (added by aaron, 15 years ago)

Patch with slightly altered test, but no documentation

  • django/db/models/query.py

     
    359359        assert kwargs, \
    360360                'get_or_create() must be passed at least one keyword argument'
    361361        defaults = kwargs.pop('defaults', {})
     362        lookup = kwargs.copy()
     363        for f in self.model._meta.fields:
     364            if f.column in lookup:
     365                lookup[f.name] = lookup.pop(f.column)
    362366        try:
    363367            self._for_write = True
    364             return self.get(**kwargs), False
     368            return self.get(**lookup), False
    365369        except self.model.DoesNotExist:
    366370            try:
    367371                params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
     
    374378            except IntegrityError, e:
    375379                transaction.savepoint_rollback(sid, using=self.db)
    376380                try:
    377                     return self.get(**kwargs), False
     381                    return self.get(**lookup), False
    378382                except self.model.DoesNotExist:
    379383                    raise e
    380384
  • tests/regressiontests/get_or_create_regress/models.py

     
    3838>>> p.books.count()
    39391
    4040
     41# Use the publisher's primary key instead of a model instance.
     42>>> book, created = Book.objects.get_or_create(publisher_id=p.id, name='The Great Book of Ed')
     43>>> created
     44True
     45>>> book.publisher == p
     46True
     47
    4148#
    4249# ManyRelatedManager
    4350#
Back to Top