Skip to content

Instantly share code, notes, and snippets.

@ketanbhatt
Last active October 19, 2023 12:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ketanbhatt/0475bb5ea6e1696f063e222baaec421f to your computer and use it in GitHub Desktop.
Save ketanbhatt/0475bb5ea6e1696f063e222baaec421f to your computer and use it in GitHub Desktop.
Update with Last modified time Django auto_now fields
def update_with_last_modified_time(qs, **kwargs):
# This function adds any auto_now field to the update call because QuerySet.update() doesn't do it :X
model_fields = qs.model._meta.get_fields()
fields_and_value_map = {}
for field in model_fields:
try:
auto_now = field.__getattribute__('auto_now')
except AttributeError:
auto_now = False
if auto_now:
if type(field) == DateField:
fields_and_value_map[field.name] = datetime.date.today()
elif type(field) == DateTimeField:
fields_and_value_map[field.name] = timezone.now()
fields_and_value_map.update(kwargs)
return qs.update(**fields_and_value_map)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment