开发者

how to retrieve data from a foreign key

开发者 https://www.devze.com 2023-01-30 01:37 出处:网络
been coding since morning and i cant get any data from the auth_user. i made a class in my model. here\'s the code:

been coding since morning and i cant get any data from the auth_user. i made a class in my model. here's the code:

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)

in my DjangoUser model, i want to get the first_name...

what will i code in my view file to retrieve the first name of the author?

thanks a lot. your answers i greatly appreciated...


As it says in the auth documentation, the user model contains a first_name attribute.

# 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

However, you should really read Storing Additional Information About the User in the same auth documentation page. It explains the correct way to build a profile for the User object. This way, the profile is stored beside the User, leaving the User object pristine. This is by design since you can use the get_profile() method to dig into that profile.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号