Remove duplicate entries in peewee

久未见 提交于 2019-12-11 04:14:30

问题


I have a quick function that I threw up together to remove duplicates on my table given a particular combination of fields:

for l in table.select():
    if table.select().where((table.Field1==l.Field1) & (table.Field2==l.Field2) & ....).count()>1:
        l.delete()
        l.save()

But I imagine that there's a better way to do this


回答1:


You could add a unique constraint on the columns you wish to be unique, then let the database enforce the rules for you. That'd be the best way.

For peewee, that looks like:

class MyModel(Model):
    first_name = CharField()
    last_name = CharField()
    dob = DateField()

    class Meta:
        indexes = (
            (('first_name', 'last_name', 'dob'), True),
        )

Docs: http://docs.peewee-orm.com/en/latest/peewee/models.html#indexes-and-unique-constraints



来源:https://stackoverflow.com/questions/27365752/remove-duplicate-entries-in-peewee

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!