Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango ORM - How to combine annotate and filter
    text
    copied!<p>I have the following models:</p> <pre><code>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) </code></pre> <p>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.</p> <p>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:</p> <pre><code>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)) </code></pre> <p>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.</p> <p>Ideally in the template I want to do something like:</p> <pre><code>{% if author.fav %} &lt;p&gt;This is one of your favorite authors&lt;/p&gt; {% endif %} </code></pre> <p>Any advice is appreciated.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload