SQLAlchemy:如何按两个字段分组并按日期过滤

15 投票
1 回答
37157 浏览
提问于 2025-04-15 23:59

我有一个表格,里面有一个时间戳和两个字段,我想确保这两个字段在过去一个月内是唯一的。

table.id
table.datestamp
table.field1
table.field2

也就是说,在过去一个月里,不能有相同的字段1和字段2组合的重复记录。

我脑子里想的步骤是:

  1. 先把这两个字段分组
  2. 然后查看过去一个月的数据,确保这个唯一的组合没有出现过。

我已经做到这一步了,但我觉得这样做不太行:

result = session.query(table).group_by(\
    table.field1,
    table.field2,
    func.month(table.timestamp))

不过我不太确定怎么在sqlalchemy里实现这个。有人能给我点建议吗?

非常感谢!

1 个回答

28

下面的内容应该能给你一些帮助,另外请注意代码中的注释:

qry = (session.query(
         table.c.field1,
         table.c.field2,    

        # #strftime* for year-month works on sqlite; 
            
        # @todo: find proper function for mysql (as in the question)
        # Also it is not clear if only MONTH part is enough, so that
        # May-2001 and May-2009 can be joined, or YEAR-MONTH must be used
        func.strftime('%Y-%m', table.c.datestamp),
        func.count(),
    )
    # optionally check only last 2 month data (could have partial months)
    .filter(table.c.datestamp < datetime.date.today() - datetime.timedelta(60))
    .group_by(
            table.c.field1,
            table.c.field2,
            func.strftime('%Y-%m', table.c.datestamp),
            )
    # comment this line out to see all the groups
    .having(func.count()>1)
  )

撰写回答