Opened 5 years ago

Last modified 5 years ago

#30053 closed New feature

Allow for conditional QuerySet.update_or_create() — at Version 3

Reported by: Joshua Cannon Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords: QuerySet update_or_create
Cc: Nasir Hussain, Adam Johnson Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Joshua Cannon)

QuerySet.update_or_create() is great since it lifts the burden of thread-safety and repeated code from the client. However there exists some scenarios where the "update" logic should be hidden behind a condition. (E.g. only update if the value of a DateTimeField is less than some value). There isn't much help for clients in these scenarios, with the best solution being to copy+paste QuerySet.update_or_create() and wrap the setattr-and-save logic in a conditional (worst case being they roll their own code, which likely would lead to thread-safety issues)

The condition would most likely be a callable that accepts one argument, the gotten instance.

The solution should be trivial, either:

  1. Add a "condition" parameter to update_or_create() (along with logic to make the feature backwards compatible, likely checking if the value is callable with one argument or not, since "condition" could be a field)
  2. Add another method, and re-write update_or_create() in terms of the new method with a condition that is always true.

Change History (3)

comment:1 by Joshua Cannon, 5 years ago

Description: modified (diff)

comment:2 by Simon Charette, 5 years ago

Could you detail your use case a bit more? I'm not sure I understand how adding a condition to the if created statement would allow you to put updates behind a condition given it's only reached when the row gets created.

Also, have you experimented with chaining filter().update_or_create() to limit its application to a filtered domain?

Last edited 5 years ago by Simon Charette (previous) (diff)

comment:3 by Joshua Cannon, 5 years ago

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