summaryrefslogtreecommitdiff
path: root/django
diff options
context:
space:
mode:
authorGary Wilson Jr <gary.wilson@gmail.com>2008-08-01 23:16:59 +0000
committerGary Wilson Jr <gary.wilson@gmail.com>2008-08-01 23:16:59 +0000
commit2db4b134809e162a6aa142300a1df14638eeae94 (patch)
tree380335351c5dc9afd081c7d5ebf8ecf876ef1161 /django
parentb5c5e8b4c06823fc3a14268a6e106e3fb6807813 (diff)
Fixed #8070 -- Cache related objects passed to Model init as keyword arguments. Also:
* Model init no longer performs a database query to refetch the related objects it is passed. * Model init now caches unsaved related objects correctly, too. (Previously, accessing the field would raise `DoesNotExist` error for `null=False` fields.) * Added tests for assigning `None` to `null=True` `ForeignKey` fields (refs #6886). git-svn-id: http://code.djangoproject.com/svn/django/trunk@8185 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django')
-rw-r--r--django/db/models/base.py16
1 files changed, 9 insertions, 7 deletions
diff --git a/django/db/models/base.py b/django/db/models/base.py
index 53307dc14c..7d7def3bad 100644
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -200,6 +200,7 @@ class Model(object):
# keywords, or default.
for field in fields_iter:
+ rel_obj = None
if kwargs:
if isinstance(field.rel, ManyToOneRel):
try:
@@ -216,17 +217,18 @@ class Model(object):
# pass in "None" for related objects if it's allowed.
if rel_obj is None and field.null:
val = None
- else:
- try:
- val = getattr(rel_obj, field.rel.get_related_field().attname)
- except AttributeError:
- raise TypeError("Invalid value: %r should be a %s instance, not a %s" %
- (field.name, field.rel.to, type(rel_obj)))
else:
val = kwargs.pop(field.attname, field.get_default())
else:
val = field.get_default()
- setattr(self, field.attname, val)
+ # If we got passed a related instance, set it using the field.name
+ # instead of field.attname (e.g. "user" instead of "user_id") so
+ # that the object gets properly cached (and type checked) by the
+ # RelatedObjectDescriptor.
+ if rel_obj:
+ setattr(self, field.name, rel_obj)
+ else:
+ setattr(self, field.attname, val)
if kwargs:
for prop in kwargs.keys():