I have a rather complex Django model that includes some fields that should only be saved under certain circumstances. As a simple example,
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=200)
counter = models.IntegerField(default=0)
def increment_counter(self):
self.counter = models.F('counter') + 1
self.save(update_fields=['counter'])
Here I use the expressions F to avoid race conditions when increasing the counter. Usually I don’t want to store the counter value outside the function increment_counter
, as this could potentially cancel the increment called from another thread or process.
So the question is, what is the best way to exclude certain default fields in the model save function? I tried the following
def save(self, **kwargs):
if update_fields not in kwargs:
update_fields = set(self._meta.get_all_field_names())
update_fields.difference_update({
'counter',
})
kwargs['update_fields'] = tuple(update_fields)
super().save(**kwargs)
ValueError: The following fields do not exist in this model or are m2m fields: id
. , , id
m2m , , , self._meta.get_all_field_names()
, update_fields
.
, django; model_obj.save()
update_fields
.