Migrate Django model to unique_together constraint

前端 未结 1 1255
滥情空心
滥情空心 2021-02-05 16:54

I have a model with three fields

class MyModel(models.Model):
    a    = models.ForeignKey(A)
    b    = models.ForeignKey(B)
    c    = models.ForeignKey(C)


        
相关标签:
1条回答
  • 2021-02-05 17:28

    If you are happy to choose one of the duplicates arbitrarily, I think the following might do the trick. Perhaps not the most efficient but simple enough and I guess you only need to run this once. Please verify this all works yourself on some test data in case I've done something silly, since you are about to delete a bunch of data.

    First we find groups of objects which form duplicates. For each group, (arbitrarily) pick a "master" that we are going to keep. Our chosen method is to pick the one with lowest pk

    from django.db.models import Min, Count
    
    master_pks = MyModel.objects.values('A', 'B', 'C'
        ).annotate(Min('pk'), count=Count('pk')
        ).filter(count__gt=1
        ).values_list('pk__min', flat=True)
    

    we then loop over each master, and delete all its duplicates

    masters = MyModel.objects.in_bulk( list(master_pks) )
    
    for master in masters.values():
        MyModel.objects.filter(a=master.a, b=master.b, c=master.c
            ).exclude(pk=master.pk).del_ACCIDENT_PREVENTION_ete()
    
    0 讨论(0)
提交回复
热议问题