Skip to content Skip to sidebar Skip to footer

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).

Solution 2:

latest() method returns the latest object which is an instance of UserChallengeSummary, which doesn't have an update method.

For updating single objects, your method is standard.

update() method is used for updating multiple objects at once, so it works on QuerySet instances.

Post a Comment for "How To Update Model Object In Django?"