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

File 9029-get-or-create-r14733.diff, 2.4 KB (added by Tai Lee, 14 years ago)

Updated tests to apply cleanly against r14733.

  • django/db/models/query.py

     
    369369        assert kwargs, \
    370370                'get_or_create() must be passed at least one keyword argument'
    371371        defaults = kwargs.pop('defaults', {})
     372        lookup = kwargs.copy()
     373        for f in self.model._meta.fields:
     374            if f.column in lookup:
     375                lookup[f.name] = lookup.pop(f.column)
    372376        try:
    373377            self._for_write = True
    374             return self.get(**kwargs), False
     378            return self.get(**lookup), False
    375379        except self.model.DoesNotExist:
    376380            try:
    377381                params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
     
    384388            except IntegrityError, e:
    385389                transaction.savepoint_rollback(sid, using=self.db)
    386390                try:
    387                     return self.get(**kwargs), False
     391                    return self.get(**lookup), False
    388392                except self.model.DoesNotExist:
    389393                    raise e
    390394
  • tests/regressiontests/get_or_create_regress/tests.py

     
    2121        # Add an author to the book.
    2222        ed, created = book.authors.get_or_create(name="Ed")
    2323        self.assertTrue(created)
    24         # Book should have one author.
     24        # The book should have one author.
    2525        self.assertEqual(book.authors.count(), 1)
    2626
    2727        # Try get_or_create again, this time nothing should be created.
     
    5151        # Now Ed has two Books, Fred just one.
    5252        self.assertEqual(ed.books.count(), 2)
    5353        self.assertEqual(fred.books.count(), 1)
     54
     55        # Use the publisher's primary key value instead of a model instance.
     56        _, created = ed.books.get_or_create(name='The Great Book of Ed', publisher_id=p.id)
     57        self.assertTrue(created)
     58        # Try get_or_create again, this time nothing should be created.
     59        _, created = ed.books.get_or_create(name='The Great Book of Ed', publisher_id=p.id)
     60        self.assertFalse(created)
     61        # The publisher should have three books.
     62        self.assertEqual(p.books.count(), 3)
Back to Top