我有这个 Django 模型(来自 Django CMS):
class Placeholder(models.Model):
slot = models.CharField(_("slot"), max_length=50, db_index=True)
default_width = models.PositiveSmallIntegerField(_("width"), null=True)
我想删除具有重复“插槽”值的占位符对象,只保留第一个并删除其他对象。
我如何编写执行此操作的查询(使用 Django QuerySet API)?
最佳答案
您可以尝试 Torsten 解决方案,但改用字典会快得多。
existing_slots = {}
for placeholder in Placeholder.objects.all():
if existing_slots.get(placeholder.slot, False):
placeholder.delete()
else:
existing_slots[placeholder.slot] = True
关于django - 删除在特定字段中具有重复值的 Django QuerySet 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5480953/