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
添加回答
舉報