I have a model that has four fields. How do I remove duplicate objects from my database?
Daniel Roseman’s answer to this question seems appropriate, but I’m not sure how to extend this to situation where there are four fields to compare per object.
Thanks,
W.
You shouldn’t do it often. Use
unique_togetherconstraints on database instead.This leaves the record with the biggest
idin the DB. If you want to keep the original record (first one), modify the code a bit withmodels.Min. You can also use completely different field, like creation date or something.Underlying SQL
When annotating django ORM uses
GROUP BYstatement on all model fields used in the query. Thus the use of.values()method.GROUP BYwill group all records having those values identical. The duplicated ones (more than oneidforunique_fields) are later filtered out inHAVINGstatement generated by.filter()on annotatedQuerySet.The duplicated records are later deleted in the
forloop with an exception to the most frequent one for each group.Empty .order_by()
Just to be sure, it’s always wise to add an empty
.order_by()call before aggregating aQuerySet.The fields used for ordering the
QuerySetare also included inGROUP BYstatement. Empty.order_by()overrides columns declared in model’sMetaand in result they’re not included in the SQL query (e.g. default sorting by date can ruin the results).You might not need to override it at the current moment, but someone might add default ordering later and therefore ruin your precious delete-duplicates code not even knowing that. Yes, I’m sure you have 100% test coverage…
Just add empty
.order_by()to be safe. 😉https://docs.djangoproject.com/en/3.2/topics/db/aggregation/#interaction-with-default-ordering-or-order-by
Transaction
Of course you should consider doing it all in a single transaction.
https://docs.djangoproject.com/en/3.2/topics/db/transactions/#django.db.transaction.atomic