Reputation: 45932
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?
Upvotes: 2
Views: 4892
Reputation: 3461
You should be able to use a OneToOneField(User, related_name='profile')
in your UserProfile model and then do Post.objects.select_related('author__profile')
.
Upvotes: 11