coffee-grinder
coffee-grinder

Reputation: 27610

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?

Upvotes: 2

Views: 3132

Answers (2)

Rafen
Rafen

Reputation: 158

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

Upvotes: 5

Torsten Engelbrecht
Torsten Engelbrecht

Reputation: 13496

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)

Upvotes: 4

Related Questions