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 delet开发者_如何转开发e 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?
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
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)
精彩评论