A Django app for adding object tools for models in the admin
Project description
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 outputs 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?'}, )
https://docs.djangoproject.com/en/stable/ref/models/querysets/#update-or-create
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:
https://docs.djangoproject.com/en/stable/ref/models/instances/#specifying-which-fields-to-save
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
Built Distributions
Hashes for dj_obj_update-0.5.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | b1cf2e310687886a0af688841f27988f2b2f9dbcb87b6fd4e9a16f121c7d051c |
|
MD5 | c50a6491f6f4c8e6e86ce61512d21780 |
|
BLAKE2b-256 | 8e0f44d505ff6a96caf58fa08e48699a6e7a97bbfb6687c006d6a9f7a3c76423 |
Hashes for dj_obj_update-0.5.0-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 615de810f8d44cce5d9200590481165ff6dea34f73536936f4dc58a7eaed0d77 |
|
MD5 | e3246fd47ecbca0d5890567ae8deb94e |
|
BLAKE2b-256 | b3ea4f9706eaa89aee2731779106363c7a4b6d4d3a250fbeb7f6d08b6b05020d |