如何从外键中检索数据

时间:2010-12-13 08:37:01

标签: django django-models django-admin

从早上开始编码,我无法从auth_user获取任何数据。我在模特里上了一堂课。这是代码:

from django.contrib.auth.models import User as DjangoUser
......
class Author(models.Model):
    """
    Data model that holds posts' authors as shown in author pages
    """
    django_user = models.ForeignKey(DjangoUser, primary_key=True)
    about = models.TextField('About', null=True, blank=True)
    avatar = ImageWithThumbsField('Pic', upload_to=settings.PATH_AVATAR, blank=True, null=True, sizes=settings.SIZES_AVATAR)

在我的DjangoUser模型中,我想获得first_name ...

我将在视图文件中编码以检索作者的名字?

非常感谢。你的回答我非常感谢...

1 个答案:

答案 0 :(得分:1)

正如auth documentation中所述,用户模型包含first_name属性。

# get the author from the database using a user as a primary key
user = User.objects.get(id=1)
author = Author.objects.get(user)

# display the author's first name by accessing the 
# User model first, then its properties
author.django_user.first_name

但是,您应该在同一个身份验证文档页面中阅读Storing Additional Information About the User。它解释了为User对象构建配置文件的正确方法。这样,配置文件存储在旁边用户,使用户对象保持原样。这是设计使然,因为您可以使用get_profile()方法深入了解该配置文件。