sync from local backup
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
from django.http import JsonResponse
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.parsers import JSONParser
|
||||
from django.db import transaction
|
||||
from ..models import Tool, ToolFavorite
|
||||
|
||||
|
||||
class ToolFavoriteToggleView(APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
parser_classes = [JSONParser]
|
||||
|
||||
@transaction.atomic
|
||||
def post(self, request, tool_id):
|
||||
try:
|
||||
tool = Tool.objects.get(pk=tool_id, is_enabled=True)
|
||||
except Tool.DoesNotExist:
|
||||
return JsonResponse({'success': False, 'error': '工具不存在'}, status=404)
|
||||
|
||||
favorite, created = ToolFavorite.objects.get_or_create(
|
||||
user=request.user,
|
||||
tool=tool
|
||||
)
|
||||
if not created:
|
||||
favorite.delete()
|
||||
is_favorite = False
|
||||
message = '已取消收藏'
|
||||
else:
|
||||
is_favorite = True
|
||||
message = '已添加收藏'
|
||||
|
||||
favorite_count = ToolFavorite.objects.filter(tool=tool).count()
|
||||
|
||||
return JsonResponse({
|
||||
'success': True,
|
||||
'data': {
|
||||
'id': tool.id,
|
||||
'is_favorite': is_favorite,
|
||||
'favorite_count': favorite_count
|
||||
},
|
||||
'message': message
|
||||
})
|
||||
|
||||
|
||||
class ToolFavoriteListView(APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def get(self, request):
|
||||
favorites = ToolFavorite.objects.select_related('tool', 'tool__category').filter(
|
||||
user=request.user,
|
||||
tool__is_enabled=True
|
||||
).order_by('-created_at')
|
||||
|
||||
data = [{
|
||||
'id': fav.tool.id,
|
||||
'name': fav.tool.name,
|
||||
'description': fav.tool.description,
|
||||
'icon': fav.tool.icon,
|
||||
'url_path': fav.tool.url_path,
|
||||
'color': fav.tool.color,
|
||||
'category': fav.tool.category.id if fav.tool.category else None,
|
||||
'category_name': fav.tool.category.name if fav.tool.category else '',
|
||||
'is_favorite': True,
|
||||
'favorite_count': ToolFavorite.objects.filter(tool=fav.tool).count(),
|
||||
'created_at': fav.created_at.isoformat()
|
||||
} for fav in favorites]
|
||||
|
||||
return JsonResponse({
|
||||
'success': True,
|
||||
'data': {
|
||||
'count': len(data),
|
||||
'results': data
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
class ToolFavoriteStatusView(APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def get(self, request, tool_id):
|
||||
is_favorite = ToolFavorite.objects.filter(
|
||||
user=request.user,
|
||||
tool_id=tool_id
|
||||
).exists()
|
||||
|
||||
favorite_count = ToolFavorite.objects.filter(tool_id=tool_id).count()
|
||||
|
||||
return JsonResponse({
|
||||
'success': True,
|
||||
'data': {
|
||||
'tool_id': tool_id,
|
||||
'is_favorite': is_favorite,
|
||||
'favorite_count': favorite_count
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user