Skip to content

Instantly share code, notes, and snippets.

@NurElHuda
Forked from kipanshi/gist:3859962
Created February 16, 2021 22:30
Show Gist options
  • Save NurElHuda/f4db576fb04ad43b21c6a1963b171476 to your computer and use it in GitHub Desktop.
Save NurElHuda/f4db576fb04ad43b21c6a1963b171476 to your computer and use it in GitHub Desktop.
Django refresh and update model instance helpers
def refresh(instance):
"""Select and return instance from database.
Usage: ``instance = refresh(instance)``
"""
return instance.__class__.objects.get(pk=instance.pk)
def update(instance, **data):
"""Update instance with data directly by using ``update()``
skipping calling ``save()`` method.
Usage: ``instance = update(instance, some_field=some_value)``
"""
instance.__class__.objects.filter(pk=instance.pk).update(**data)
return refresh(instance)
@NurElHuda
Copy link
Author

Very helpful, just what I was looking for. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment