#26426: Use case for QuerySet.extra: annotate query with the existence of a
relation
-------------------------------+----------------------------
Reporter: yourcelf | Owner: nobody
Type: Uncategorized | Status: new
Component: Uncategorized | Version: 1.9
Severity: Normal | Keywords: QuerySet.extra
Triage Stage: Unreviewed | Has patch: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------+----------------------------
This ticket is just to document a use case for QuerySet.extra as requested
by the docs:
https://docs.djangoproject.com/en/1.9/ref/models/querysets/#extra
I have a Category model like this:
{{{
class Category(models.Model):
name = models.CharField(max_length=200)
followers = models.ManyToManyField(User)
}}}
I want to get a list of all categories, but to annotate each category with
whether the currently logged in user is a "follower" of the category.
Neither `prefetch_related` nor `annotate` work here, because I don't want
to fetch nor aggregate over //all// "followers" (potentially many), I just
want the presence of the current user. The extra query looks like this:
{{{
Category.objects.filter(...).extra(
select={'is_following': '''EXISTS(
SELECT "id" FROM "projects_category_followers" WHERE
"projects_category_followers"."category_id"="projects_category"."id" AND
"projects_category_followers"."user_id"=%s
)'''},
select_params=(request.user.id,)
)
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/26426>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/051.476918d9a4b7c437478fabd7df21186a%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.