Opened 3 years ago

Last modified 2 years ago

#32879 closed Uncategorized

Using annotate and extra in ORM — at Version 1

Reported by: Zerq Owned by: nobody
Component: Database layer (models, ORM) Version: 3.2
Severity: Normal Keywords: QuerySet.extra
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Zerq)

In simple example:

class Foo(models.Model):
     pass
class Bar(models.Model):
     baz = models.ForeignKey('Foo', on_delete=models.PROTECT)

I want to count reverse relation count and then select_for_update:

Foo.objects.annotate(Count('bar')).select_for_update().get(...)

but this does not work: django.db.utils.NotSupportedError: FOR UPDATE is not allowed with GROUP BY clause

To circumvent this problem I used:

Foo.extra(select={'bar_count': 'SELECT COUNT(*) FROM "app_bar" U0 WHERE U0."baz_id" = "app_foo"."id"'}).select_for_update().get(...)

I file this issue to show usage of extra, as asked in documentation.

Change History (1)

comment:1 by Zerq, 3 years ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top