Fixed #9029 -- Allow use of fieldname_id with get_or_create. Thanks to aaron and mrmachine.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@15156 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Andrew Godwin 2011-01-08 13:27:30 +00:00
parent 32a344dfe2
commit 81e05a418d
2 changed files with 16 additions and 3 deletions

View File

@ -369,9 +369,13 @@ class QuerySet(object):
assert kwargs, \ assert kwargs, \
'get_or_create() must be passed at least one keyword argument' 'get_or_create() must be passed at least one keyword argument'
defaults = kwargs.pop('defaults', {}) defaults = kwargs.pop('defaults', {})
lookup = kwargs.copy()
for f in self.model._meta.fields:
if f.column in lookup:
lookup[f.name] = lookup.pop(f.column)
try: try:
self._for_write = True self._for_write = True
return self.get(**kwargs), False return self.get(**lookup), False
except self.model.DoesNotExist: except self.model.DoesNotExist:
try: try:
params = dict([(k, v) for k, v in kwargs.items() if '__' not in k]) params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
@ -384,7 +388,7 @@ class QuerySet(object):
except IntegrityError, e: except IntegrityError, e:
transaction.savepoint_rollback(sid, using=self.db) transaction.savepoint_rollback(sid, using=self.db)
try: try:
return self.get(**kwargs), False return self.get(**lookup), False
except self.model.DoesNotExist: except self.model.DoesNotExist:
raise e raise e

View File

@ -21,7 +21,7 @@ class GetOrCreateTests(TestCase):
# Add an author to the book. # Add an author to the book.
ed, created = book.authors.get_or_create(name="Ed") ed, created = book.authors.get_or_create(name="Ed")
self.assertTrue(created) self.assertTrue(created)
# Book should have one author. # The book should have one author.
self.assertEqual(book.authors.count(), 1) self.assertEqual(book.authors.count(), 1)
# Try get_or_create again, this time nothing should be created. # Try get_or_create again, this time nothing should be created.
@ -51,3 +51,12 @@ class GetOrCreateTests(TestCase):
# Now Ed has two Books, Fred just one. # Now Ed has two Books, Fred just one.
self.assertEqual(ed.books.count(), 2) self.assertEqual(ed.books.count(), 2)
self.assertEqual(fred.books.count(), 1) self.assertEqual(fred.books.count(), 1)
# Use the publisher's primary key value instead of a model instance.
_, created = ed.books.get_or_create(name='The Great Book of Ed', publisher_id=p.id)
self.assertTrue(created)
# Try get_or_create again, this time nothing should be created.
_, created = ed.books.get_or_create(name='The Great Book of Ed', publisher_id=p.id)
self.assertFalse(created)
# The publisher should have three books.
self.assertEqual(p.books.count(), 3)