4

我在这里遇到了一个奇怪的问题,我的一对一关系似乎没有反向工作。用代码来解释是最容易的。

我已经扩展了默认的 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 字段,但不是关系?我不确定如何访问它并避免此错误。

提前感谢任何人可以提供的任何帮助。

4

1 回答 1

4

当您指定related_name 时,您不会向User模型添加字段。相反,创建了某种描述符,因此它不会在User'fields属性中可见。以这种方式在TaskUser模型中定义字段意味着不可能有TaskUser没有关联用户的实例,但可能有User没有关联TaksUser实例的实例(关系同样如此ForeignKey),因此您需要确保该TaskUser实例是实际创建的;它不会自动完成。

于 2013-05-19T15:30:05.043 回答