删除peewee中的重复条目 [英] Remove duplicate entries in peewee

查看:320
本文介绍了删除peewee中的重复条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个快速功能,可以结合特定的字段组合一起删除表上的重复项:

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

推荐答案

您可以在希望唯一的列上添加唯一约束,然后让数据库为您强制执行规则.那是最好的方法.

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

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

这篇关于删除peewee中的重复条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆