Error "Can not update identity column 'order'"

0

For an old project need, the developer of the time created a field in the table that is not a primary key but is self-incrementing, but django returns an error because it can not update that field. The use of Django's AutoField type is intended for the primary key, it can not be used in that case, but I do not know if there is any way to map the table correctly.

Example of a template representing the video table.

class Video(models.Model):
    id = UUIDField(db_column='ID', default=uuid.uuid4, auto=True)
    titulo = models.CharField(null=False, max_length=200, db_column='DsVideo')
    order = models.IntegerField(db_column='order')

The field "order" is that this in the database is auto incremental, but when saving, the error Can not update identity column 'order' is returned.

    
asked by anonymous 13.11.2015 / 02:21

1 answer

0

In this SOen question the author has found a temporary workaround, which is to remove problematic query of insertion / update. Adapted to your code:

class Video(models.Model):
    id = UUIDField(db_column='ID', default=uuid.uuid4, auto=True)
    titulo = models.CharField(null=False, max_length=200, db_column='DsVideo')
    order = models.IntegerField(db_column='order')

    def save(self, *args, **kwargs):
        if self.order is not None:
            self._meta.local_fields = [f for f in self._meta.local_fields if f.name != 'order']

As the DBMS itself is responsible for updating this field, the fact that Django ignores it in writing (but still give you the option of accessing it for reading) should not be a problem. Note: the question is old (2011), I can not guarantee that the technique will still work in current versions of Django.

    
17.11.2015 / 14:23