Django无法从User对象访问用户配置文件数据

时间:2018-03-13 06:30:28

标签: django django-models

我有这样的个人资料模型:

class UserProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile')
    about = models.TextField()

当我尝试从UserProfile实例访问User数据时,我收到此错误:

In [1]: 

In [1]: from django.contrib.auth.models import User

In [5]: u = User.objects.all()[0]

In [6]: u
Out[6]: <User: admin>

In [13]: u.profile
---------------------------------------------------------------------------
RelatedObjectDoesNotExist                 Traceback (most recent call last)
<ipython-input-13-679bed70444a> in <module>()
----> 1 u.profile

~/project/djangoedu/env/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py in __get__(self, instance, cls)
    402                 "%s has no %s." % (
    403                     instance.__class__.__name__,
--> 404                     self.related.get_accessor_name()
    405                 )
    406             )

RelatedObjectDoesNotExist: User has no profile.

In [14]: u.author
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-327f8c8449fd> in <module>()
----> 1 u.author

AttributeError: 'User' object has no attribute 'author'

In [15]: 

2 个答案:

答案 0 :(得分:1)

来自docs

A DoesNotExist exception is raised when accessing the reverse relationship if an entry in the related table doesn’t exist.

因此,在访问用户个人资料之前,您需要先创建此个人资料:

u = User.objects.all()[0]
UserProfile.objects.create(user=u)

答案 1 :(得分:0)

尝试这样

from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.ForeignKey(User, related_name="profile")