2010-12-13 43 views
0

自早晨開始編碼,我無法從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

正如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 

但是,您應該在相同的auth文檔頁面中真正閱讀Storing Additional Information About the User。它解釋了爲User對象構建配置文件的正確方法。通過這種方式,配置文件被存儲在旁邊用戶,留下原始的用戶對象。這是通過設計,因爲您可以使用get_profile()方法挖掘該配置文件。

+0

this code:author = Author.objects.get(id = 1);會得到以下錯誤:無法將關鍵字「ID」解析爲字段。選擇是:about,avatar,django_user;因爲在作者班只有那些領域.. – EVG 2010-12-13 09:09:18

+0

謝謝。代碼固定。雖然適當的Django配置文件路線是我仍然推薦的路線。 – Soviut 2010-12-13 17:55:53