how can I get users with their userprofiles?
I have my own comments app
Model:
APPS = (
(1, 'Game'),
(2, 'Article'),
(3, 'CMS'),
(4, 'User profile'),
)
comment_type = models.IntegerField(choices=APPS,
default=1,
verbose_name="Comment Type")
object_id = models.IntegerField(default=0)
user = models.ForeignKey(User, null = True, blank = False, related_name='user')
View:
context = {
...
'comments': Comment.objects.filter(comment_type=1, object_id=game_id),
...
}
UserProfile:
class UserProfile(models.Model):
user = models.OneToOneField(User)
signature = models.TextField(blank=True)
And my view:
{% for comment in comments %}
....
{{ comment.user.profile.signature }}
{% endfor %}
I am django rookie. Thank you.
You can simply use .select_related() here, as Comment already has a foreign key to User, and User has a foreign key to Profile:
.prefetch_related() does a separate lookup for each query. .select_related() grabs everything in one statement.