gpt4 book ai didi

python - 阻止 Django 插入或更新 SQL Server 计算列

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:32 25 4
gpt4 key购买 nike

我有一个如下所示的 Django 模型:

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 不会尝试插入或更新这些特定列?

最佳答案

我在 save 方法中进行了这项工作,以忽略计算的 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)

关于python - 阻止 Django 插入或更新 SQL Server 计算列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27300054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com