【发布时间】: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? 有没有更好的办法?
【问题讨论】:
-
这可能有助于查找和删除重复的stackoverflow.com/questions/23908971/…
标签: django postgresql add-custom-command