Last active
October 19, 2023 12:20
-
-
Save ketanbhatt/0475bb5ea6e1696f063e222baaec421f to your computer and use it in GitHub Desktop.
Update with Last modified time Django auto_now fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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