{{{
from django.db import models
from django.utils import timezone
class Foo(models.Model):
num = models.IntegerField(default=0)
date = models.DateTimeField(default=timezone.now)
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`.
--
Ticket URL: <https://code.djangoproject.com/ticket/28616>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* cc: felixxm (added)
--
Ticket URL: <https://code.djangoproject.com/ticket/28616#comment:1>
* stage: Unreviewed => Accepted
--
Ticket URL: <https://code.djangoproject.com/ticket/28616#comment:2>
* status: new => assigned
* owner: nobody => messfish
--
Ticket URL: <https://code.djangoproject.com/ticket/28616#comment:3>
* owner: nobody => Anvesh Mishra
* status: new => assigned
--
Ticket URL: <https://code.djangoproject.com/ticket/28616#comment:3>
Comment (by Anvesh Mishra):
Should we add a support for this behavior or stick to
`NotImplementedError` ?
--
Ticket URL: <https://code.djangoproject.com/ticket/28616#comment:4>
* cc: Anvesh Mishra (added)
* owner: Anvesh Mishra => (none)
* status: assigned => new
--
Ticket URL: <https://code.djangoproject.com/ticket/28616#comment:5>
* owner: (none) => Anvesh Mishra
* status: new => assigned
Comment:
On looking into it further it seems like the problem comes because of how
the `QuerySet.update()` works
{{{ #!python
query = self.query.chain(sql.UpdateQuery)
}}}
The Query.chain() changes the class of the current object to UpdateQuery
which removes the previous query as a new object is created i.e
{{{
SELECT DISTINCT ON ("distinct_foo"."num") "distinct_foo"."id",
"distinct_foo"."num", "distinct_foo"."date", "distinct_foo"."flag" FROM
"distinct_foo" ORDER BY "distinct_foo"."num" ASC, "distinct_foo"."date"
DESC
}}}
and then replaces it with
{{{
UPDATE "app_foo" SET "flag" = true; args=(True)
}}}
instead of combining both.
--
Ticket URL: <https://code.djangoproject.com/ticket/28616#comment:6>