I have the following models:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True, related_name='profile')
starred_authors = models.ManyToManyField(Author, related_name='users_with_stars')
class Author(models.Model):
name = models.CharField(max_length=250)
slug = models.SlugField(unique=True)
And then in the author template, I would like to show whether or not the currently logged in user has starred that author, but I am running into trouble constructing a suitable query to get this data with the ORM.
In the view I had thought to annotate an author object with a count that will be 0 if the author has not been starred, or 1 if starred. Something like this:
def author_detail(request, slug):
user_id = request.user.pk
author = Author.objects.filter(slug=slug).filter(users_with_stars__user__pk=user_id).annotate(fav=Count('users_with_stars'))[0]
return render_to_response('app/author_detail.html',
{ 'author': author},
context_instance=RequestContext(request))
But the above is no good because no objects are found if the current user hasn’t starred the author. What I would like to do is somehow put the last filter inside the annotate, but I haven’t been able to get that working.
Ideally in the template I want to do something like:
{% if author.fav %}
<p>This is one of your favorite authors</p>
{% endif %}
Any advice is appreciated.
I would probably split this out into a separate property in the template dictionary and calculate it by checking directly whether this user is in the list of users that starred this author.
Something like:
And in the template: