简体   繁体   中英

Django: using user.get_profile()

I have a very newbie question on using django auth. Here is my model:

class UserProfile(models.Model):
    """ Main user profile used on a website """
    user            = models.ForeignKey(User, unique=True) # reference to built in django user
    display_name    = models.CharField(max_length=100, blank=True)
    # and several more fields

class Post(models.Model):
    """ Blog entry """
    author          = models.ForeignKey(User)
    tags            = models.ManyToManyField(Tag)
    title           = models.CharField(max_length=255)
    text            = models.TextField()

Trouble comes, when I want to output a list of posts:

#view
posts = Post.objects.all()
#template
{% for post in posts %}
    {{ post.title }} by {{ post.author.get_profile.display_name }}
{% endfor %}

For 100 posts this gives 101 queries, because every get_profile() goes to database to get the display_name field.

Is there a way to fix this? Can I use select_related() , or something? Or should I be referencing UserProfile istead of User in my Post model?

您应该能够在UserProfile模型中使用OneToOneField(User, related_name='profile') ,然后执行Post.objects.select_related('author__profile')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM