如何让peewee在结果查询中将相关表行的ids放入额外的列表字段中?
我想为媒体文件制作复制检测管理器。对于我的PC上的每个文件,我在数据库中都有记录,字段如下
File name, Size, Path, SHA3-512, Perceptual hash, Tags, Comment, Date added, Date changed, etc...根据不同的情况,我希望使用不同的模式将表中的记录视为副本。
在最简单的情况下,我只想看到具有相同散列的所有记录,所以我
subq = Record.select(Record.SHA).group_by(Record.SHA).having(peewee.fn.Count() > 1)
subq = subq.alias('jq')
q = Record.select().join(q, on=(Record.SHA == q.c.SHA)).order_by(Record.SHA)
for r in q:
process_record_in_some_way(r)一切都很好。但在很多情况下,我希望使用不同的表列集合作为分组模式。所以在最坏的情况下,我使用除了id和"Date added“列之外的所有行来检测数据库中的精确重复行,当我只读取相同的文件几次时,这会导致像这样的怪物
subq = Record.select(Record.SHA, Record.Name, Record.Date, Record.Size, Record.Tags).group_by(Record.SHA, Record.Name, Record.Date, Record.Size, Record.Tags).having(peewee.fn.Count() > 1)
subq = subq.alias('jq')
q = Record.select().join(q, on=(Record.SHA == q.c.SHA and Record.Name == q.c.Name and Record.Date == q.c.Date and Record.Size == q.c.Size and Record.Tags == q.c.Tags)).order_by(Record.SHA)
for r in q:
process_record_in_some_way(r)这不是我的字段的完整列表,只是举例。对于字段集的其他模式,我也必须做同样的事情,例如,在select子句中复制它的列表3次,在子查询的grouping子句中,然后在joining子句中再次列出它们。
我希望我可以用适当的模式对记录进行分组,peewee只会将每个组中所有成员的I列在新的列表字段中,如下所示
q=Record.select(Record, SOME_MAJIC.alias('duplicates')).group_by(Record.SHA, Record.Name, Record.Date, Record.Size, Record.Tags).having(peewee.fn.Count() > 1).SOME_ANOTHER_MAJIC
for r in q:
process_group_of_records(r) # r.duplicates == [23, 44, 45, 56, 100], for example我该怎么做呢?列出相同的参数时,我真的觉得我做错了什么。
发布于 2019-01-26 03:38:37
您可以使用GROUP_CONCAT (或者对于postgres,array_agg)对ids/文件名列表进行分组和连接。
因此,对于具有相同散列的文件:
query = (Record
.select(Record.sha, fn.GROUP_CONCAT(Record.id).alias('id_list'))
.group_by(Record.sha)
.having(fn.COUNT(Record.id) > 1))这是一个关系数据库。因此,无论何时何地,您都在处理由行和列组成的表。没有“嵌套”。GROUP_CONCAT几乎是你能得到的最接近的了。
https://stackoverflow.com/questions/54365255
复制相似问题