#32879: Using extra instead annotate in ORM while using select_for_update
-------------------------------------+-------------------------------------
Reporter: Zerq | Owner: nobody
Type: Uncategorized | Status: closed
Component: Database layer | Version: 3.2
(models, ORM) |
Severity: Normal | Resolution: duplicate
Keywords: QuerySet.extra | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by George Tantiras):
Replying to [comment:4 Zerq]:
> For anyone who have the same problem:
>
> {{{
> sub =
Subquery(Bar.objects.filter(pk=OuterRef('pk')).annotate(count=Count('*')).values('count'))
> sub = Coalesce(sub, 0)
> query = Foo.objects.annotate(times_used=sub)
> }}}
>
> Small warning: If subquery has no values, it will return None, this is
the reason for Coalesce.
The above code returns incorrect results compared to the results brought
by the following query:
{{{
query =
Foo.objects.annotate(times_used=Count(F("bar"))).values("times_used")
}}}
The query that managed to bring the same results, according to the docs
about [https://docs.djangoproject.com/en/dev/ref/models/expressions
/#using-aggregates-within-a-subquery-expression using aggregates within a
subquery expression] and
[https://docs.djangoproject.com/en/dev/ref/models/expressions/#func-
expressions-1 func expressions] is the following:
{{{
sub =
Subquery(Bar.objects.filter(baz=OuterRef('pk')).order_by().annotate(count=Func(F("id"),
function="Count")).values_count("count"))
query = Foo.objects.annotate(times_used=Coalesce(sub, 0))
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/32879#comment:5>
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 view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/010701809a27bbe5-e9d2101a-8a9f-4040-bea4-2c38f1832aa4-000000%40eu-central-1.amazonses.com.