Opened 4 years ago

Last modified 4 years ago

#28616 assigned Bug

DISTINCT ON and update() does the wrong thing

Reported by: Daniel Keller Owned by: messfish
Component: Database layer (models, ORM) Version: 1.11
Severity: Normal Keywords:
Cc: Mariusz Felisiak Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


If I have a model like

from django.db import models
from django.utils import timezone

class Foo(models.Model):
    num = models.IntegerField(default=0)
    date = models.DateTimeField(
    flag = models.BooleanField(default=False)

and (with Postgresql) I do

Foo.objects.order_by('num', '-date').distinct('num').only('pk')

I get a query like

SELECT DISTINCT ON ("app_foo"."num") "app_foo"."id" AS Col1 FROM "app_foo" ORDER BY "app_foo"."num" ASC, "app_foo"."date" DESC; args=()

which returns the latest Foo for each num.

BUT, if I do

Foo.objects.order_by('num', '-date').distinct('num').update(flag=True)

then it executes

UPDATE "app_foo" SET "flag" = true; args=(True)

which updates everything.

I don't necessarily think that this behaviour should be supported, but it would be nice to at least get a NotImplementedError.

Change History (3)

comment:1 Changed 4 years ago by Mariusz Felisiak

Cc: Mariusz Felisiak added

comment:2 Changed 4 years ago by Tim Graham

Triage Stage: UnreviewedAccepted

comment:3 Changed 4 years ago by messfish

Owner: changed from nobody to messfish
Status: newassigned
Note: See TracTickets for help on using tickets.
Back to Top