Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Django QuerySet objects with a duplicate value in a particular field

I have this Django model (from Django CMS):

class Placeholder(models.Model):
    slot = models.CharField(_("slot"), max_length=50, db_index=True)
    default_width = models.PositiveSmallIntegerField(_("width"), null=True)

I want to delete the Placeholder objects with a duplicate 'slot' value, keeping only the first one of each and deleting the others.

How do I write a query (using the Django QuerySet API) that does this?

like image 987
coffee-grinder Avatar asked Nov 30 '25 01:11

coffee-grinder


2 Answers

You can try Torsten solution but using a dictionary instead, is way much faster.

existing_slots = {}
for placeholder in Placeholder.objects.all():
    if existing_slots.get(placeholder.slot, False):
        placeholder.delete()
    else:
        existing_slots[placeholder.slot] = True
like image 82
Rafen Avatar answered Dec 03 '25 05:12

Rafen


I would do a functional approach, rather than one particular query which does all of this:

existing_slots = []
for placeholder in Placeholder.objects.all():
    if placeholder.slot in existing_slots:
        placeholder.delete()
    else:
        existing_slots.append(placeholder.slot)
like image 34
Torsten Engelbrecht Avatar answered Dec 03 '25 06:12

Torsten Engelbrecht



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!