python - Better way to set default value in django model field -
i implementing field in django model calls following function default value
def get_default_value(): = mymodel.objects.aggregate(max_id=max('id')) return get_unique_value_based_on_num(a['max_id'] or 0) class mymodel: default_value_field = charfield(default=get_default_value)
although may wrong on this, fear implementation may result in race condition.
is there better way ? may use f object or else ?
to avoid race conditions, best letting database handle integrity of table, 1 of things databases made for.
to so, catch integrityerror
raised saving model instance , try again different value when fails.
from django.db import integrityerror, models, transaction def get_default_value(): = mymodel.objects.aggregate(max_id=max('id')) return get_unique_value_based_on_num(a['max_id'] or 0) class mymodel(models.model): # have unicity enforced @ database level unique=true. default_value_field = models.charfield(max_length=200, unique=true) def save(self): if not self.default_value_field: max_tries = 100 # choose sensible value! in range(max_tries): try: self.default_value_field = get_default_value() # atomic block rollback transaction in case of integrityerror. transaction.atomic(): super(mymodel, self).save() break except integrityerror: # default_value_field not unique, try again new value. continue else: # max tries reached, raise. raise integrityerror('could not save model because etc...') else: super(mymodel, self).save(*args, **kwargs)
Comments
Post a Comment