我使用 PyODBC 连接到旧数据库。有些模型可以很好地插入和更新,但这个模型不行。当我们使用 ORM 获取现有记录时,它会尝试在保存时执行插入而不是更新
class PurchaseOrder(models.Model):
purchaseorderid = models.BigAutoField(db_column='PurchaseOrderId', primary_key=True)
ticketnumber = models.CharField(db_column='TicketNumber', unique=True, max_length=20, blank=True, null=True)
customer = models.ForeignKey('Customer', to_field='local_id', db_column='CustId', on_delete=models.DO_NOTHING)
# a bunch of other irrelevant columns
class Meta:
managed = False
db_table = 'PurchaseOrders'
在外壳(或其他任何地方的代码)中,我可以获取现有的采购订单,甚至打印它的 pk 就可以了:
>>> po = PurchaseOrder.objects.all()[76543] # grab a random existing po
>>> print(po.pk)
78730
但是当我去保存记录时,应该进行更新——我们已经验证了 pk 存在——它尝试进行插入,但由于重复的 pk 而失败:
>>> po.save()
Traceback (most recent call last):
File "/home/django/.env/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
文件“/home/django/.env/lib/python3.10/site-packages/mssql/base.py”,第621行,执行中 返回 self.cursor.execute(sql, params) pyodbc.IntegrityError: ('23000', "[23000] [Microsoft][SQL Server 的 ODBC 驱动程序 17][SQL Server]违反主键约束 'PK_PurchaseOrders_1'。无法在对象 'dbo.PurchaseOrders' 中插入重复的键。重复的键值是 (78730)。(2627) (SQLExecDirectW)")
如果我将模型更改为使用整数字段而不是自动字段,它会再次尝试插入而不是更新并失败:
class PurchaseOrder(models.Model):
purchaseorderid = models.IntegerField(db_column='PurchaseOrderId', primary_key=True)
>>> po = PurchaseOrder.objects.all()[74563]
>>> print(po.pk)
76703
>>> po.save()
Traceback (most recent call last):
File "/home/django/.env/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "/home/django/.env/lib/python3.10/site-packages/mssql/base.py", line 621, in execute
return self.cursor.execute(sql, params)
pyodbc.IntegrityError: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot insert explicit value for identity column in table 'PurchaseOrders' when IDENTITY_INSERT is set to OFF. (544) (SQLExecDirectW)")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/lib/python3.10/code.py", line 90, in runcode
exec(code, self.locals)
File "<console>", line 1, in <module>
File "/home/django/.env/lib/python3.10/site-packages/django/db/models/base.py", line 814, in save
self.save_base(
File "/home/django/.env/lib/python3.10/site-packages/django/db/models/base.py", line 877, in save_base
updated = self._save_table(
File "/home/django/.env/lib/python3.10/site-packages/django/db/models/base.py", line 1020, in _save_table
results = self._do_insert(
File "/home/django/.env/lib/python3.10/site-packages/django/db/models/base.py", line 1061, in _do_insert
return manager._insert(
File "/home/django/.env/lib/python3.10/site-packages/django/db/models/manager.py", line 87, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/django/.env/lib/python3.10/site-packages/django/db/models/query.py", line 1805, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/home/django/.env/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1822, in execute_sql
cursor.execute(sql, params)
File "/home/django/.env/lib/python3.10/site-packages/django/db/backends/utils.py", line 102, in execute
return super().execute(sql, params)
File "/home/django/.env/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(
File "/home/django/.env/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/django/.env/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute
with self.db.wrap_database_errors:
File "/home/django/.env/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/django/.env/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "/home/django/.env/lib/python3.10/site-packages/mssql/base.py", line 621, in execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server] [SQL Server]Cannot insert explicit value for identity column in table 'PurchaseOrders' when IDENTITY_INSERT is set to OFF. (544) (SQLExecDirectW)")
有人知道为什么当记录具有明确定义的 pk 时 Django 会窒息并尝试插入吗?我们直接从 ORM 获取记录,那么为什么它认为这是一条新记录呢?
因为
managed=False
是为 PurchaseOrder
型号设置的。我假设您通过其他方式创建了此模型(例如:使用数据库中的 SQL DDL 语句手动创建)。如果是这种情况,字段 purchaseorderid
可能在数据库中没有主键。数据库中可能还有另一个字段是主键。
调试此问题的简单方法是
print(p.pk)
和 print(p.purchaseorderid)
并比较两者。
或者您可以使用数据库查看器工具(例如 Dbeaver)来查看数据库的状态并进行验证。