Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Looking at the <code>add_aggregate</code> function within <code>django/db/models/sql/query.py</code>, query objects will not be accepted as input values.</p> <p>Unfortunately, there is currently no direct way within Django to aggregate/annotate on what amounts to a queryset, especially not one that is additionally filtered somehow.</p> <p>Assuming the following models:</p> <pre><code>class Item(models.Model): name = models.CharField(max_length=32) class Tag(models.Model): itemfk = models.ForeignKey(Item, related_name='tags') name = models.CharField(max_length=32) class FavoritedTag(models.Model): user = models.ForeignKey(User) tag = models.ForeignKey(Tag) </code></pre> <p>Also, you cannot annotate a queryset on fields defined via <code>.extra()</code>.</p> <p>One could drop into SQL in <code>views.py</code> like so:</p> <pre><code>from testing.models import Item, Tag, FavoritedTag from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.utils.datastructures import SortedDict @login_required def interest_level(request): ruid = request.user.id qs = Item.objects.extra( select = SortedDict([ ('interest_level', 'SELECT COUNT(*) FROM testing_favoritedtag, testing_tag \ WHERE testing_favoritedtag.user_id = %s \ AND testing_favoritedtag.tag_id = testing_tag.id \ AND testing_tag.itemfk_id = testing_item.id'), ]), select_params = (str(ruid),) ) return render_to_response('testing/interest_level.html', {'qs': qs}) </code></pre> <p>Template:</p> <pre><code>{% for item in qs %} name: {{ item.name }}, level: {{ item.interest_level }}&lt;br&gt; {% endfor %} </code></pre> <p>I tested this using MySQL5. Since I'm no SQL expert though, I'd be curious as to how to optimize here, or if there is another way to "lessen" the amount of SQL. Maybe there is some interesting way to utilize the <code>related_name</code> feature here directly within SQL?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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