Note that there are some explanatory texts on larger screens.

plurals
  1. POPrevent Django from updating identity column in MSSQL
    primarykey
    data
    text
    <p>I'm working with a legacy DB in MSSQL. We have a table that has two columns that are causing me problems: </p> <pre><code>class Emp(models.Model): empid = models.IntegerField(_("Unique ID"), unique=True, db_column=u'EMPID') ssn = models.CharField(_("Social security number"), max_length=10, primary_key=True, db_column=u'SSN') # Field name made lowercase. </code></pre> <p>So the table has the ssn column as primary key and the relevant part of the SQL-update code generated by django is this: </p> <pre><code>UPDATE [EMP] SET [EMPID] = 399, ......... WHERE [EMP].[SSN] = 2509882579 </code></pre> <p>The problem is that EMP.EMPID is an identity field in MSSQL and thus pyodbc throws this error whenever I try to save changes to an existing employee: </p> <pre><code>ProgrammingError: ('42000', "[42000] [Microsoft][SQL Native Client][SQL Server]C annot update identity column 'EMPID'. (8102) (SQLExecDirectW); [42000] [Microsof t][SQL Native Client][SQL Server]Statement(s) could not be prepared. (8180)") </code></pre> <p>Having the EMP.EMPID as identity is not crucial to anything the program, so dropping it by creating a temporary column and copying, deleting, renaming seems like the logical thing to do. This creates one extra step in transferring old customers into Django, so my question is, is there any way to prevent Django from generating the '[EMPID] = XXX' snippet whenever I'm doing an update on this table?</p> <p><strong>EDIT</strong><br> I've patched my model up like this: </p> <pre><code>def save(self, *args, **kwargs): if self.empid: self._meta.local_fields = [f for f in self._meta.local_fields if f.name != 'empid'] super().save(*args, **kwargs) </code></pre> <p>This works, taking advantage of the way Django populates it's sql-sentence in django/db/models/base.py (525). If anyone has a better way or can explain why this is bad practice I'd be happy to hear it!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload