Last active
          April 28, 2025 13:48 
        
      - 
      
- 
        Save victorono/cd9d14b013487b8b22975512225c5b4c to your computer and use it in GitHub Desktop. 
    Django - remove duplicate objects where there is more than one field to compare
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | from django.db.models import Count, Max | |
| unique_fields = ['field_1', 'field_2'] | |
| duplicates = ( | |
| MyModel.objects.values(*unique_fields) | |
| .order_by() | |
| .annotate(max_id=Max('id'), count_id=Count('id')) | |
| .filter(count_id__gt=1) | |
| ) | |
| for duplicate in duplicates: | |
| ( | |
| MyModel.objects | |
| .filter(**{x: duplicate[x] for x in unique_fields}) | |
| .exclude(id=duplicate['max_id']) | |
| .delete() | |
| ) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Thank you so much! This is EXACTLY what I needed to fix an issue with one of my migrations taking forever.