Search code examples
djangodjango-cmsdjango-querysetdjango-shell

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?


Solution

  • 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)