Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I guess, this would work:</p> <pre><code>Comment.objects.filter(*[ ~Q(id__in=user.comments.order_by('-created')[3:].values_list('id', flat=True)) for user in User.objects.all() ]) </code></pre> <p>However, it seems like neither pythonic nor efficient way to solve the problem. (Efficiency problem could be somewhat solved by using cache, but still.)</p> <p>What are you trying to achieve, anyway? You could just fetch all user's comments and use only the latest three. Assuming that your comments are ordered by <code>-created</code> field:</p> <pre><code>{% for user in users %} {% for comment in user.comments.all|slice:"3" %}{{ comment }}{% endfor %} {% endfor %} </code></pre> <p>Slicing will be converted to <code>LIMIT</code> clause in SQL query, so you won't be getting all the comments anyway. Of course, there would be more that one query executed to get all the comments, so using template caching can help.</p> <p>Again, this may not make sense in your case. If it doesn't, it would be better if you clarify the requirements.</p> <h3>Raw SQL</h3> <p>If you know how to do what you want with raw SQL ([1] may help), then you need to just find a way to put it into <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#extra" rel="nofollow noreferrer"><code>extra()</code></a> somehow ([2] is an example of complex extra query which may give you an idea).</p> <p>[1] <a href="https://stackoverflow.com/questions/2590169/how-to-select-a-limited-amount-of-rows-for-each-foreign-key">How to select a limited amount of rows for each foreign key?</a></p> <p>[2] <a href="https://stackoverflow.com/questions/3293874/djangos-extrawhere-clauses-are-clobbered-by-table-renaming-filterfoo-in">django&#39;s .extra(where= clauses are clobbered by table-renaming .filter(foo__in=... subselects</a></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