我在这里遇到了一个奇怪的问题,我的一对一关系似乎没有反向工作。用代码来解释是最简单的。
我扩展了默认的Django User来添加时区,如下所示:
#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 with User,它可以同步其他所有内容,没有问题。
因此,根据文档,我现在应该在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字段,但不是作为关系?我不太确定如何访问它并避免此错误。
提前感谢任何人提供的帮助。
当您指定related_name时,您没有向User
模型添加字段。相反,创建了某种描述符,因此它在User
的fields
属性中不可见。在TaskUser
模型中以这种方式定义字段意味着没有关联用户的TaskUser
实例是不可能的,但是没有关联TaksUser
实例的User
实例是可能的(对于ForeignKey
关系也是如此),因此您需要确保实际创建了TaskUser
实例;它不会自动完成的。