【发布时间】:2019-01-25 12:21:20
【问题描述】:
如何让 peewee 将相关表行的 id 放入额外的类似列表的字段中到结果查询中?
我想为媒体文件制作重复检测管理器。对于我电脑上的每个文件,我都在数据库中记录了类似的字段
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 和“添加日期”列之外的所有这些列来检测数据库中精确的重复行,而我只是读取了同一个文件几次,这会导致怪物像
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 次,子查询的分组子句,然后在 join 子句中再次列出它们。
我希望我可以用适当的模式对记录进行分组,peewee 只会将每个组的所有成员的 id 列出到新的列表字段中,例如
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
我该怎么做?三次列出相同的参数我真的觉得我做错了什么。
【问题讨论】:
-
注意使用 Python 的“and”是行不通的。因此,您的“怪物”示例实际上并没有像您想象的那样起作用。您需要在每个表达式周围使用括号并将它们与“&”连接在一起 - 二进制和。请参阅此处的注释:docs.peewee-orm.com/en/latest/peewee/query_operators.html
标签: python database sqlite orm peewee