Opened 3 years ago

Last modified 3 years ago

#32879 closed Uncategorized

Using annotate and extra in ORM — at Initial Version

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

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(...)

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top