如何在Django中处理React传入的选中任务并返回共同推荐地图?
实现选中Quest的共同推荐地图查询(Django)
完全可行,以下是两种高效的实现方式:
方法一:利用Django ORM的聚合查询(推荐)
这种方式通过数据库层面的聚合筛选,性能更优,适合数据量较大的场景。假设前端通过POST请求传递选中的Quest ID列表quest_ids:
from django.db.models import Count from rest_framework.views import APIView from rest_framework.response import Response from .models import Map class CommonMapsAPI(APIView): def post(self, request): quest_ids = request.data.get("quest_ids", []) if not quest_ids: return Response([]) # 筛选被所有选中Quest共同推荐的Map common_maps = Map.objects.filter( quests__id__in=quest_ids ).annotate( # 统计每个Map被多少个选中的Quest推荐 matched_quest_count=Count("quests") ).filter( # 只保留被所有选中Quest都推荐的Map matched_quest_count=len(quest_ids) ).values("id", "name") # 返回前端需要的字段 return Response(common_maps)
逻辑说明:
- 先筛选出至少被一个选中Quest推荐的Map;
- 给每个Map标注被选中Quest推荐的次数;
- 最终筛选出标注次数等于选中Quest总数的Map,这些就是所有选中Quest的共同推荐地图。
方法二:通过集合交集实现(适合小数据量)
如果选中的Quest数量不多,也可以先获取第一个Quest的推荐地图,再依次和其他Quest的推荐地图求交集:
from rest_framework.views import APIView from rest_framework.response import Response from .models import Quest class CommonMapsAPI(APIView): def post(self, request): quest_ids = request.data.get("quest_ids", []) if not quest_ids: return Response([]) # 初始化共同地图集合为第一个Quest的推荐地图 common_maps = Quest.objects.get(id=quest_ids[0]).recommended_map.all() # 遍历剩余Quest,逐步求交集 for quest_id in quest_ids[1:]: current_quest_maps = Quest.objects.get(id=quest_id).recommended_map.all() common_maps = common_maps.intersection(current_quest_maps) # 如果中途交集为空,可提前终止循环 if not common_maps.exists(): break # 转换为前端需要的字典格式 result = [{"id": map.id, "name": map.name} for map in common_maps] return Response(result)
前端只需将选中的Quest ID数组通过POST请求发送到上述API接口,就能获取到共同推荐的地图列表。
内容的提问来源于stack exchange,提问作者Hyuenjun
相关产品推荐
相关产品推荐

