How To Update Model Object In Django?
I am using below code for update the status. current_challenge = UserChallengeSummary.objects.filter(user_challenge_id=user_challenge_id).latest('id') current_challenge.update(stat
Solution 1:
Your working solution is the way usually used in Django, as @Compadre already said.
But sometimes (for example, in tests) it's useful to be able to update multiple fields at once. For such cases I've written simple helper:
defupdate_attrs(instance, **kwargs):
""" Updates model instance attributes and saves the instance
:param instance: any Model instance
:param kwargs: dict with attributes
:return: updated instance, reloaded from database
"""
instance_pk = instance.pk
for key, value in kwargs.items():
ifhasattr(instance, key):
setattr(instance, key, value)
else:
raise KeyError("Failed to update non existing attribute {}.{}".format(
instance.__class__.__name__, key
))
instance.save(force_update=True)
return instance.__class__.objects.get(pk=instance_pk)
Usage example:
current_challenge = update_attrs(current_challenge,
status=str(request.data['status']),
other_field=other_value)
# ... etc.
If you with, you can remove instance.save()
from the function (to call it explicit after the function call).
Post a Comment for "How To Update Model Object In Django?"