Django多重For循环批量更新Athlete模型最新ASP预约字段问题
问题解决方法
问题原因
你当前的代码逻辑仅会提取所有预约记录里全局最新的那一条对应的数据,仅更新对应单个运动员的字段,没有按照运动员分组统计每一位的最新预约记录,所以无法实现所有运动员的字段批量更新。
最优实现方案(Django ORM原生方法,效率更高)
使用Django自带的聚合查询直接按运动员分组拿到最新预约日期,无需手动遍历所有记录:
from django.db.models import Max, Count # 按运动员ID分组,查询每个运动员的最新预约日期、预约总次数 athlete_booking_stats = ASPBookings.objects.filter( booking_date__isnull=False ).values('athlete_id').annotate( latest_date=Max('booking_date'), total_sessions=Count('id') ) update_athletes = [] for stat in athlete_booking_stats: athlete = Athlete.objects.get(id=stat['athlete_id']) athlete.latest_asp_session = stat['latest_date'] athlete.number_asp_sessions = stat['total_sessions'] # 不需要更新次数字段可删除该行 update_athletes.append(athlete) # 批量更新,减少数据库查询次数,数据量大时性能优势明显 Athlete.objects.bulk_update(update_athletes, ['latest_asp_session', 'number_asp_sessions'])
手动遍历实现方案(逻辑更直观)
如果需要用手动遍历的方式实现,可以用字典存储每个运动员的最新日期,遍历过程中实时更新:
# 初始化字典存储结构:运动员ID:最新预约日期 athlete_latest_dates = {} for booking in asp_data: if booking.booking_date is None: continue athl_id = booking.athlete_id # 运动员无记录或当前预约日期更新时,替换存储的日期 if athl_id not in athlete_latest_dates or booking.booking_date > athlete_latest_dates[athl_id]: athlete_latest_dates[athl_id] = booking.booking_date # 遍历字典更新所有运动员的对应字段 for athl_id, latest_date in athlete_latest_dates.items(): athlete = Athlete.objects.get(id=athl_id) athlete.latest_asp_session = latest_date athlete.save()
内容的提问来源于stack exchange,提问作者Mark
相关产品推荐
相关产品推荐

