我在这里遇到了一个奇怪的问题,我的一对一关系似乎没有反向工作。用代码来解释是最容易的。
我已经扩展了默认的 Django 用户以添加时区,如下所示:
#This model holds custom user fields
class TaskUser(models.Model):
user = models.OneToOneField(User, related_name="task_user")
timezone = models.CharField(max_length=50, default="UTC")
我使用 South 迁移,到目前为止没有问题。它在我的管理员中内联显示,再次没有问题。我还使用了syncdb,因为我之前没有使用过带有用户的South,它同步了其他所有内容都没有问题。
因此,根据文档,我现在应该在 User 对象上有一个字段 task_user,它引用 TaskUser 对象。
如果我进入 Django shell,情况并非如此。(见[6])
In [1]: from django.contrib.auth.models import User
In [2]: current_user = User.objects.get(pk=1)
In [3]: current_user?
Type: User
String Form:callum
File: /usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py
Docstring:
Users within the Django authentication system are represented by this
model.
Username, password and email are required. Other fields are optional.
In [4]: for field in current_user._meta.fields:
print field.name
...:
id
password
last_login
is_superuser
username
first_name
last_name
email
is_staff
is_active
date_joined
In [5]: dir(current_user)
Out[5]:
['DoesNotExist',
'Meta',
'MultipleObjectsReturned',
'REQUIRED_FIELDS',
'USERNAME_FIELD',
#I have removed many more field here
'task_user',
#And a few here
'validate_unique']
In [6]: current_user.task_user
---------------------------------------------------------------------------
DoesNotExist Traceback (most recent call last)
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <module>()
----> 1 current_user.task_user
/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.pyc in __get__(self, instance, instance_type)
277 setattr(instance, self.cache_name, rel_obj)
278 if rel_obj is None:
--> 279 raise self.related.model.DoesNotExist
280 else:
281 return rel_obj
DoesNotExist:
我对这个结果有点困惑 - 对象似乎在某处有这个 task_data 字段,但不是关系?我不确定如何访问它并避免此错误。
提前感谢任何人可以提供的任何帮助。