我有两个模型:
class Profile(models.Model):
# (...)
settings = models.OneToOneField('Settings', null=True)
# (...)
class Settings(model.Model):
# (...)
有没有办法在访问Profile#settings时创建设置实例?
更新:我想要这个的主要动机是我已经有了Profile模型,并且我希望在用户点击需要Profile#setting实例的应用程序点时懒惰地创建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