I have a table 'Comments' 开发者_运维百科and inside field the 'user', I would get in addition to the profile Profile in the same query. Currently I have something like that
comments = models.Comment.objects.select_related('author__profile').filter(post=article)
Unfortunately I can not retrieve information about profile, I can only get to it through
comment.author._profile_set_cache
Any ideas to make it look nice like?
comment.author.profile
If the 'author' is from the contrib.auth User model, then you don't have a FK to the UserProfile. It is a "reverse one-to-one". Fortunately, django is able to navigate a reverse one-to-one using "select_related", so the query is actually retrieving the fields (you can check it by using
print models.Comment.objects.select_related('author__profile').filter(post=article).query
The way to get the profile of a user is with the get_profile()
method:
print comment.author.get_profile()
As the profile data is already cached (that's why the _profile_set_cache is for), getting the object means no additional query.
精彩评论