python - Django: How to delete duplicate rows based on 2 columns? -
i found out in this answer can delete duplicate rows (duplication based on n columns) in table raw sql.
is there equivalence using django orm ? stuff found in django concerned duplicated based on 1 column only.
note : know there way prevent future duplicates (based on several fields) in django, using unique_together
field (but didn't know before).
thanks.
a direct translation sql in other answer django orm:
from django.db.models import min # first select min ids min_id_objects = mymodel.objects.values('a', 'b').annotate(minid=min('id')) min_ids = [obj['minid'] obj in min_id_objects] # delete mymodel.objects.exclude(id__in=min_ids).delete()
this results in 2 separate sql queries instead of 1 nested sql provided in other answer. think enough.
Comments
Post a Comment