python - 如何阻止 Django/PSQL 在创建失败时自动递增表 ID

标签 python django postgresql psql

目前,我有一个 Django 项目,其中有一个 ItemReport 表,该表每天只允许每个项目 1 个条目。一切都很好,除了每当它因 IntegrityError 失败时(即我的项目尝试在 ItemReport 已经存在的那一天创建一个 ItemReport ,对象 ID 无论如何都会递增) .

例如:

September 1:
 Report for September 1 (ID 1)

September 2:
 Report for September 1 (ID 1)
 Report for September 2 (ID 5)

型号如下:

class ItemReport(BaseModel):
    fk_item: Item = models.ForeignKey(Item, null=False)
    date = models.DateField(default=now, null=False)

    class Meta:
        unique_together=(('fk_item', 'date'),)


class Item(BaseModel):
    item_class = models.CharField(max_length=40, null=False)
    name = models.CharField(max_length=80, unique=True, null=False)

每次用户登录时运行的代码:

    for i in Item.objects.all():
        try:
            latest_ir = ItemReport.objects.create(fk_item=i)
            print('Created Item Report!')
        except IntegrityError as e:
            print('ItemReport for {} for today already exists!'.format(i.name))
    print('Created ItemReports!\n')

最佳答案

在你提出这个问题三年后,我遇到了同样的问题,并且发现这个问题在 SO 中还没有得到解答,我想在这里留下我如何解决这个问题的方法,以供 future 的访问者使用。

以前,我使用下面的代码来防止重复错误。

try:
    m = Modal(title='Title', content='Content.')
    m.save()
except IntegrityError:
    pass

但我遇到了和你一样的问题,每当它因 IntegrityError 失败时,对象 ID 都会递增。

我通过删除 try/except block 并使用 get_or_create() 而不是 save() 解决了这个问题。

Modal.objects.get_or_create(title='Title', content='Content.')

Django文档中对get_or_create()方法的详细解释: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#get-or-create

关于python - 如何阻止 Django/PSQL 在创建失败时自动递增表 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46049924/

相关文章:

python - python numpy数组操作+=线程安全吗?

django - 使用@require_POST 时如何在 Django 中显示 HTTP 状态 405(不允许的方法)的自定义错误页面

django m2m_changed 信号通过模型自定义

postgresql - sqlalchemy/postgresql : get database 'as-of' timestamp of a query

python - SQLAlchemy 查询返回 None

python - 在进程中每隔一段时间执行一次任务

x 轴上的 python/matplotlib 箱线图

python - 在使用 readlines() 创建的字符串中使用 for 循环插入多行

python-3.x - Django ORM 错误 - 无法将 NULL 插入主键

postgresql - SQL中两个日期范围的重叠(以分钟为单位)