【问题标题】:Django - remove duplicates records from DBDjango - 从数据库中删除重复记录
【发布时间】:2018-04-09 11:57:26
【问题描述】:

我想在我的数据库(postgres)上设置“unique_together”。问题是我可能已经在 DB 上有重复项,因此迁移可能不起作用。所以正如我所看到的 - 在部署之前,我需要运行一些脚本来删除所有重复项(每个只保留一个)。我更喜欢用 Django 自定义命令来做。

“映射”表类似于 - Id、user_id、user_role、project_id、user_type。 我想为所有这些设置“unique_together”。 我用来检索重复行的脚本是-

duplicates = (Mapping.objects.values('project_id', 'user_id', 'user_type', 'user_role').annotate(
        count=Count('id')).values('project_id', 'user_id', 'user_type', 'user_role').order_by().
           filter(count__gt=1))

它返回包含重复属性的对象列表。 例如:

QuerySet [{'user_id': '2222', 'user_type': '1', 'user_role': '1', 'project_id': UUID('c02bda0e-5488-4519-8f34-96b7f3d36fd6')}, {'user_id': '44444', 'user_type': '1', 'user_role': '1', 'project_id': UUID('8c088f57-ad0c-411b-bc2f-398972872324')}]>

有没有办法直接检索 ID? 有没有更好的办法?

【问题讨论】:

标签: django postgresql add-custom-command


【解决方案1】:

你可以试试:

Mapping.objects.values(
    'project_id', 'user_id', 'user_type', 'user_role'
).annotate(count=Count('id')
).annotate(max_id=Max('id')
).values('max_id').order_by().filter(count__gt=1)

【讨论】:

  • 我收到以下错误,因为 'id' 是 UUID - LINE 1: SELECT MAX("mapping"."id") AS "max_id" FROM ... ^ 提示:否函数匹配给定的名称和参数类型。您可能需要添加显式类型转换。但据我了解,它假设只返回行,对吗?
  • 在您的情况下,问题在于 id 类型,您使用 uuid 并且数据库无法将 max 函数应用于此类字段,您可以为 uuid 指定自定义函数,例如,您可以在此处查看: [PostgreSQL 创建 UUID 最大聚合函数 ](gist.github.com/devodo/8b39748d65e8185fbd89),对不起,现在我无法为您提供更多帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
  • 2010-10-14
相关资源
最近更新 更多