2

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?

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

While you are at it, why not using a set() instead and drop the True. If it's efficiency you are after, a set() is more efficient from a memory point of view than a dictionary.
4

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.