From 70f9a4f6ceb1bc4a33714e3b1cfb99175e2fcf3f Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Tue, 10 Nov 2009 15:21:12 +0000 Subject: [PATCH] Fixed #12190 -- Corrected a regression in the ability to instantiate ForeignKeys outside of models. Thanks to jittat for the report. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11730 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/fields/related.py | 4 ++++ tests/regressiontests/many_to_one_regress/models.py | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index c4bd9fb983..2b27b5a340 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -695,6 +695,10 @@ class ForeignKey(RelatedField, Field): assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) else: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) + # For backwards compatibility purposes, we need to *try* and set + # the to_field during FK construction. It won't be guaranteed to + # be correct until contribute_to_class is called. Refs #12190. + to_field = to_field or (to._meta.pk and to._meta.pk.name) kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = rel_class(to, to_field, diff --git a/tests/regressiontests/many_to_one_regress/models.py b/tests/regressiontests/many_to_one_regress/models.py index 3f35bef62c..d491f002c2 100644 --- a/tests/regressiontests/many_to_one_regress/models.py +++ b/tests/regressiontests/many_to_one_regress/models.py @@ -167,4 +167,10 @@ Traceback (most recent call last): ... ValueError: Cannot assign "": "Child.parent" must be a "Parent" instance. +# Regression for #12190 -- Should be able to instantiate a FK +# outside of a model, and interrogate its related field. +>>> cat = models.ForeignKey(Category) +>>> cat.rel.get_related_field().name +'id' + """}