如何在Sql Server引发错误时阻止自动字段更新?

时间:2016-07-02 00:27:54

标签: python django sql-server-2008 django-models

我有这个主键: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]

1 个答案:

答案 0 :(得分:1)

在插入标记时,不是测试标记是否相同,而是查询数据库以查看是否有任何标记相同。如果没有返回任何内容,请添加:

if not Transaction.objects.get(token=new_token):
       # do whatever