From dc473309ef15e88a41845a52485eb6d38f819637 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Fri, 23 Jun 2006 08:16:36 +0000 Subject: [PATCH] Fixed #1661 -- Added logic for string-form model references in the 'to' argument of OneToOneFields. Includes regression test. git-svn-id: http://code.djangoproject.com/svn/django/trunk@3197 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/fields/related.py | 7 +++++- tests/regressiontests/string_lookup/models.py | 25 +++++++++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index ad31a92c91f..5ee1aec0227 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -515,8 +515,13 @@ class ForeignKey(RelatedField, Field): class OneToOneField(RelatedField, IntegerField): def __init__(self, to, to_field=None, **kwargs): + try: + to_name = to._meta.object_name.lower() + except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT + assert isinstance(to, basestring), "OneToOneField(%r) is invalid. First parameter to OneToOneField must be either a model, a model name, or the string %r" % (to, RECURSIVE_RELATIONSHIP_CONSTANT) + else: + to_field = to_field or to._meta.pk.name kwargs['verbose_name'] = kwargs.get('verbose_name', '') - to_field = to_field or to._meta.pk.name if kwargs.has_key('edit_inline_type'): import warnings diff --git a/tests/regressiontests/string_lookup/models.py b/tests/regressiontests/string_lookup/models.py index 7dd31f572db..a4582ca4e9c 100644 --- a/tests/regressiontests/string_lookup/models.py +++ b/tests/regressiontests/string_lookup/models.py @@ -21,9 +21,22 @@ class Whiz(models.Model): def __str__(self): return "Whiz %s" % self.name +class Child(models.Model): + parent = models.OneToOneField('Base') + name = models.CharField(maxlength = 50) + + def __str__(self): + return "Child %s" % self.name + +class Base(models.Model): + name = models.CharField(maxlength = 50) + + def __str__(self): + return "Base %s" % self.name + API_TESTS = """ -# Regression test for #1662: Check that string form referencing of models works, both as -# pre and post reference +# Regression test for #1661 and #1662: Check that string form referencing of models works, +# both as pre and post reference, on all RelatedField types. >>> f1 = Foo(name="Foo1") >>> f1.save() @@ -45,4 +58,12 @@ API_TESTS = """ >>> b1.back +>>> base1 = Base(name="Base1") +>>> base1.save() + +>>> child1 = Child(name="Child1", parent=base1) +>>> child1.save() + +>>> child1.parent + """