我有这个主键:transaction_number
当我插入带有效令牌的模型时,它会自动递增。
每当我尝试使用相同的令牌插入两个模型时,我使用异常IntegrityError
来忽略。
问题是,如果来自transaction_number的当前索引是5并且我尝试插入具有相同令牌的20个模型,则django将引发IntegrityError但索引将为25。
如何阻止索引更新?
谢谢大家
型号:
class Transaction(models.Model):
transaction_number = models.AutoField(primary_key = True)
token = models.CharField(max_length=32, unique = True)
login = models.ForeignKey(Account, related_name = 'transactions', db_column = 'login', to_field = 'login')
price = models.CharField(max_length = 7)
description = models.CharField(max_length = 25)
status = models.CharField(max_length = 25)
date = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = 'Transactions'
表:
CREATE TABLE [dbo].[Transactions](
[transaction_number] [int] IDENTITY(1,1) NOT NULL,
[token] [varchar](32) NOT NULL,
[login] [varchar](10) NOT NULL,
[price] [varchar](7) NOT NULL,
[description] [varchar](25) NOT NULL,
[status] [varchar](25) NOT NULL,
[date] [datetime] NOT NULL,
CONSTRAINT [PK_Transactions_1] PRIMARY KEY CLUSTERED
(
[transaction_number] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
答案 0 :(得分:1)
在插入标记时,不是测试标记是否相同,而是查询数据库以查看是否有任何标记相同。如果没有返回任何内容,请添加:
if not Transaction.objects.get(token=new_token):
# do whatever