[Django]-Stop Django from inserting or updating SQL Server computed column

4πŸ‘

βœ…

I went with this work around in the save method to ignore the computed SQL Server columns. Found here: Prevent Django from updating identity column in MSSQL

def save(self, force_insert=False, force_update=False, using=None,
         update_fields=None):
    # Hack to not save the maturity and months_open as they are computed columns
    self._meta.local_fields = [f for f in self._meta.local_fields if f.name not in ('maturity', 'months_open')]
    super(LocationMaster, self).save(force_insert, force_update, using, update_fields)
πŸ‘€duffn

4πŸ‘

I encountered this issue when a field is updated with PostgreSQL triggers, but django overwrites it’s value (in same transaction).

This is a generic class decorator that prevents sending enabled=False fields to database (perhaps in any query, like UPDATE).

def prevent_updating_non_editable_fields(clazz):
      """ prevents sending non`editable` fields in queries  """
      meta = clazz._meta
      meta.local_concrete_fields = [f for f in meta.local_concrete_fields if f.editable]
      return clazz


@prevent_updating_editable_fields
class MyModel(models.Model):
       precomputed = models.IntegerField(default=0, editable=False)
πŸ‘€Taha Jahangir

-3πŸ‘

You should be able to accomplish this by adding editable=False to the field.

More info here: https://docs.djangoproject.com/en/dev/ref/models/fields/#editable

πŸ‘€Abid A

Leave a comment