`dj-obj-update` helps you update an object but only saves if something changed.
Project description
Django Object Update
dj-obj-update
is a module that helps you do two things while updating
an object:
- Only do a save if something changed
- Log what changed (the logger name is
obj_update
and only outputslogging.DEBUG
)
Installation
pip install dj-obj-update
Usage
Updating an object
from obj_update import obj_update
new_data = {
'flavor': 'chocolate',
}
for obj in queryset:
obj_update(obj, new_data)
Dry run updating an object
from obj_update import obj_update
logger.setLevel(logging.DEBUG) # see "Logging changes" below
new_data = {
'flavor': 'chocolate',
}
for obj in queryset:
obj_update(obj, new_data, update_fields=[])
Replacement for update_or_create
from obj_update import obj_update_or_create
choice, created = obj_update_or_create(
Choice,
question=question,
defaults={'choice_text': 'Flour or corn?'},
)
Dealing with auto_now
fields
By default, dj-obj-update
constructs an update_fields
when it saves.
This means fields like the primary key, auto_now
, and auto_now_add
might not get saved. If you need these, you should set
update_fields=None
. Usage is the same as Django's update_fields
Logging changes
Using python-json-logger
:
import logging
from pythonjsonlogger.jsonlogger import JsonFormatter
logger = logging.getLogger('obj_update')
handler = logging.FileHandler('log/my_obj_changes.log')
handler.setFormatter(JsonFormatter())
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
With JSON logging, you'll get messages like:
{"message": "[text hello->hello2]", "model": "FooModel", "pk": 1, "changes": {"text": {"old": "hello", "new": "hello2"}}}
With a normal logger, you'll still get output, but it won't have as much information:
[text hello->hello2]
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
dj-obj-update-0.5.1.tar.gz
(10.3 kB
view hashes)
Built Distribution
Close
Hashes for dj_obj_update-0.5.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9c4ef486cf8513a702121bbf1e1830db379582ba453a2ef16c58b8234b1c303e |
|
MD5 | 1ee2b7ee2fe190129ad927ac3d27aea8 |
|
BLAKE2b-256 | 36f0c6aa7b069029332496e6ddcccc76b2db35bf331c28fc51fbeae2f790c128 |