#32433: Delete distinct produces an unexpected and potentially harmful SQL
-------------------------------------+-------------------------------------
               Reporter:  egism      |          Owner:  nobody
                   Type:             |         Status:  new
  Uncategorized                      |
              Component:  Database   |        Version:  3.1
  layer (models, ORM)                |       Keywords:  orm, delete,
               Severity:  Normal     |  distinct, postgresql
           Triage Stage:             |      Has patch:  0
  Unreviewed                         |
    Needs documentation:  0          |    Needs tests:  0
Patch needs improvement:  0          |  Easy pickings:  0
                  UI/UX:  0          |
-------------------------------------+-------------------------------------
 I was looking for a way to delete the first Comment of each Post (a sample
 domain). Since I know that every new Post starts with a system generated
 comment I decided to go with:

 `Comment.objects.order_by('post_id',
 'created_at').distinct('post_id').delete()`

 Before proceeding I tested it with:

 `Comment.objects.order_by('post_id',
 'created_at').distinct('post_id').count()`

 Made sure the result actually contains what I needed and proceeded with
 the `delete()`. The result was rather surprising. I was notified that the
 whole table was wiped clean. I then checked the actual SQL that was
 executed and it was a simple `DELETE FROM comments;`.

 As an ORM user, I would say it is the worst outcome possible and I would
 at least expect an error in such a case or ideally a SQL of what I was
 trying to achieve. At the same time, `count` and `delete` produces an
 inconsistent result which is even more mistaking.

 Potential solutions:
 * raise an error with a decent explanation
 * produce a desired SQL according to the query

-- 
Ticket URL: <https://code.djangoproject.com/ticket/32433>
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/048.4429781fe8896983dca2738564978f28%40djangoproject.com.

Reply via email to