Opened 10 years ago
Last modified 8 years ago
#26426 closed New feature
Use case for QuerySet.extra: annotate query with the existence of a relation — at Initial Version
| Reported by: | Charlie DeTar | Owned by: | nobody |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | 1.9 |
| Severity: | Normal | Keywords: | QuerySet.extra |
| Cc: | Triage Stage: | Accepted | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
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,)
)