【发布时间】:2013-03-09 00:59:25
【问题描述】:
我有两个模型:
class Profile(models.Model):
# (...)
settings = models.OneToOneField('Settings', null=True)
# (...)
class Settings(model.Model):
# (...)
有没有办法在访问 Profile#settings 时创建 Settings 的实例?
更新:我想要这个的主要动机是我已经有了 Profile 模型,并且我希望延迟创建 Setting 关系当用户点击需要 Profile#setting 实例的应用程序点时,而不关心它是否被创建。
更新: @miki725 在下面说这已经由 Django 处理了。我尝试了以下方法:
class SettingsTest(TestCase):
def setUp(self):
user = User.objects.create(username='felipe', email='something@aol.com')
self.profile = Profile.objects.create(short_name='Felipe', name='Felipe',
user=user)
def test_settings(self):
self.assertIsNotNone(self.profile.settings)
我明白了:
Creating test database for alias 'default'...
F
======================================================================
FAIL: test_settings (activity.tests.settings.SettingsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/vagrant/activity/tests/settings.py", line 20, in test_settings
self.assertIsNotNone(self.profile.settings)
AssertionError: unexpectedly None
----------------------------------------------------------------------
Ran 1 test in 0.003s
【问题讨论】:
-
您可能想解释一下您所说的访问是什么意思。可能可以通过覆盖
SettingsDoesNotExists异常或settings对象管理器来实现。 -
@Rohan 我希望当我执行
profile.settings时,我会得到一个新的 Settings 实例,其中包含所有默认字段以及与 Profile的关联> 实例到位。 -
你能举个例子吗?
-
您是否正在执行保存操作,并且您需要在保存之前为您的配置文件设置一个设置实例?
标签: python django one-to-one relation