2014-12-04 47 views
0

我有一個Django的模型,看起來像這樣:停止從Django的插入或更新的SQL Server計算列

class LocationMaster(models.Model): 
    id = models.AutoField(primary_key=True) 
    open_date = models.DateField(blank=True, null=True) 
    months_open = models.DecimalField(max_digits=18, decimal_places=2, blank=True, null=True) # Calculated column in SQL Server 
    maturity = models.CharField(max_length=50, blank=True) # Calculated column in SQL Server 

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None): 
     # ?? Something here 
     super(LocationMaster, self).save(force_insert, force_update, using, update_field) 

我的專欄中有兩個是SQL Server的計算列。我想在我的應用程序中顯示這些列,包括在管理員中,但是不要插入或更新這些列,因爲它們是計算出來的。如果沒有修改我的模型,我得到這個錯誤:

('42000', '[42000] [FreeTDS][SQL Server]The column "months_open" cannot be modified because it is either a computed column or is the result of a UNION operator. (271) (SQLExecDirectW)') 

如何修改我的模型,這樣Django不試圖插入或更新這些特定的列?

回答

2

我這個工作進展的保存方法周圍忽略計算的SQL Server列。在這裏找到: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) 
0

您應該可以通過將editable=False添加到該字段來完成此操作。

此處瞭解詳情:https://docs.djangoproject.com/en/dev/ref/models/fields/#editable

+0

感謝您的回答,但似乎並不奏效。我在兩個字段中都添加了「editable = False」,但仍收到相同的錯誤。 – duffn 2014-12-04 18:23:16

+0

什麼時候你看到錯誤? – 2014-12-04 18:53:24

+0

嘗試通過管理界面添加或更新記錄時。 – duffn 2014-12-04 19:59:03