Skip to content

Commit c28daf2

Browse files
committed
Fixed #757: manually set AutoField values are now respected; also added unit test to verify the correct behavior. Thanks, cygnus.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@1511 bcc190cf-cafb-0310-a4f2-bffc1f526a37
1 parent bf0f6ec commit c28daf2

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

AUTHORS

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,6 @@ answer newbie questions, and generally made Django that much better:
8787
wojtek
8888
8989

90-
9190
A big THANK YOU goes to:
9291

9392
Rob Curley and Ralph Gage for letting us open-source Django.

django/core/meta/__init__.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1009,8 +1009,12 @@ def method_save(opts, self):
10091009
record_exists = False
10101010
if not pk_set or not record_exists:
10111011
field_names = [db.db.quote_name(f.column) for f in opts.fields if not isinstance(f, AutoField)]
1012-
placeholders = ['%s'] * len(field_names)
10131012
db_values = [f.get_db_prep_save(f.pre_save(getattr(self, f.attname), True)) for f in opts.fields if not isinstance(f, AutoField)]
1013+
# If the PK has been manually set we must respect that
1014+
if pk_set:
1015+
field_names += [f.column for f in opts.fields if isinstance(f, AutoField)]
1016+
db_values += [f.get_db_prep_save(f.pre_save(getattr(self, f.column), True)) for f in opts.fields if isinstance(f, AutoField)]
1017+
placeholders = ['%s'] * len(field_names)
10141018
if opts.order_with_respect_to:
10151019
field_names.append(db.db.quote_name('_order'))
10161020
# TODO: This assumes the database supports subqueries.
@@ -1020,7 +1024,7 @@ def method_save(opts, self):
10201024
cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % \
10211025
(db.db.quote_name(opts.db_table), ','.join(field_names),
10221026
','.join(placeholders)), db_values)
1023-
if opts.has_auto_field:
1027+
if opts.has_auto_field and not pk_set:
10241028
setattr(self, opts.pk.attname, db.get_last_insert_id(cursor, opts.db_table, opts.pk.column))
10251029
db.db.commit()
10261030
# Run any post-save hooks.

tests/testapp/models/basic.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,14 @@ class Article(meta.Model):
157157
>>> a8.save()
158158
>>> a8.id
159159
8L
160+
161+
# You can manually specify the primary key when creating a new objet
162+
>>> a101 = articles.Article(id=101, headline='Article 101', pub_date=datetime(2005, 7, 31, 12, 30, 45))
163+
>>> a101.save()
164+
>>> a101 = articles.get_object(pk=101)
165+
>>> a101.headline
166+
'Article 101'
167+
160168
"""
161169

162170
from django.conf import settings

0 commit comments

Comments
 (0)