from django.http import JsonResponse
from .models import Book
def books_with_authors(request):
if request.method == 'POST':
# 使用 select_related 来预取 author 数据
books = Book.objects.select_related('author').all()
# 构造包含书籍和作者信息的字典列表
response_data = []
for book in books:
response_data.append({
'id': book.id,
'title': book.title,
'author': {
'id': book.author.id,
'name': book.author.name
}
})
return JsonResponse({'status': 'success', 'data': response_data})