Ticket #9029: 9029-get-or-create-r14733.diff
File 9029-get-or-create-r14733.diff, 2.4 KB (added by , 14 years ago) |
---|
-
django/db/models/query.py
369 369 assert kwargs, \ 370 370 'get_or_create() must be passed at least one keyword argument' 371 371 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) 372 376 try: 373 377 self._for_write = True 374 return self.get(** kwargs), False378 return self.get(**lookup), False 375 379 except self.model.DoesNotExist: 376 380 try: 377 381 params = dict([(k, v) for k, v in kwargs.items() if '__' not in k]) … … 384 388 except IntegrityError, e: 385 389 transaction.savepoint_rollback(sid, using=self.db) 386 390 try: 387 return self.get(** kwargs), False391 return self.get(**lookup), False 388 392 except self.model.DoesNotExist: 389 393 raise e 390 394 -
tests/regressiontests/get_or_create_regress/tests.py
21 21 # Add an author to the book. 22 22 ed, created = book.authors.get_or_create(name="Ed") 23 23 self.assertTrue(created) 24 # Book should have one author.24 # The book should have one author. 25 25 self.assertEqual(book.authors.count(), 1) 26 26 27 27 # Try get_or_create again, this time nothing should be created. … … 51 51 # Now Ed has two Books, Fred just one. 52 52 self.assertEqual(ed.books.count(), 2) 53 53 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)