3 回答

TA贡献1862条经验 获得超6个赞
解决方案 1
一个简单的方法是迭代年/月应用过滤器:
years = {sheet.year for sheet in Balance_Sheet.objects.all()}
for year in years:
year_months = {sheet.month for sheet in Balance_Sheet.objects.filter(year=year)}
for month in year_months:
object_to_update = Balance_Sheet.objects.filter(
year=year,
period=month
).order_by('-publish_date').first()
object_to_update.status = 1
object_to_update.save()
可能有更复杂的 ORM 函数来将其变成单个查询,但我在那里编写的代码(未测试)将在大多数/所有 Django 版本中工作。此外,由于我们谈论的是年/月数量,因此对数据库的查询量不会很大。
方案二
在 postgres 数据库中,你可以试试这个:
Balance_Sheet.objects.all().order_by(
'year', 'period', '-publish_date'
).distinct(
'year', 'period'
).update(
status=1
)
请注意,这不适用于其他数据库,例如 MySQL。请在此处查看 django 文档。

TA贡献1853条经验 获得超18个赞
这在 mysql 中工作
UPDATE Balance_Sheet b
INNER JOIN (SELECT max(publish_date) LastDate, year, period FROM bs GROUP BY year, period) C
ON C.LastDate = b.publish_date and C.period = b.period and C.year = b.year
SET b.status = 1
where C.LastDate = b.publish_date and C.period = b.period and C.year = b.year
谢谢大家

TA贡献1786条经验 获得超11个赞
我不熟悉 django 但它的 sql 看起来像这样。由于您已经有了资产负债表。您只需要更新部分。
WITH balance_sheet(id ,yearmonth , publish_date, status)
AS (SELECT 1, '202003', '2020-03-10' , 0 UNION
SELECT 2, '202003', '2020-03-15' , 0 UNION
SELECT 3, '202004', '2020-04-20' , 0 UNION
SELECT 4, '202004', '2020-04-25' , 0
)
UPDATE b
SET status = 1
FROM balance_sheet b
JOIN (Select *,RANK() OVER (partition by yearmonth ORDER BY publish_date desc) AS rnk
from balance_sheet bal) b_latest ON b.id = b_latest.id
WHERE b_latest.rnk = 1
添加回答
举报