mirror of
https://expo.survex.com/repositories/expoweb/.git/
synced 2025-12-08 23:04:35 +00:00
Nearly got it working, just the foreign key field to do
This commit is contained in:
@@ -5,3 +5,65 @@ there is an observed risk of overwriting each others' changes.
|
||||
|
||||
After each expo finishes, the logbook will be permanantly stored in
|
||||
the same HTML archive format we are currently using.
|
||||
|
||||
PROBLEM
|
||||
Logbookentry has author as a foreign key defined on PersonLogbookEntry,
|
||||
so it is not serializable in the Logbookentry object.
|
||||
|
||||
|
||||
Gemini has the answer:
|
||||
|
||||
from django.http import JsonResponse, HttpResponse
|
||||
# from .models import LogbookEntry, PersonLogEntry, Person # Import your models
|
||||
from django.forms.models import model_to_dict
|
||||
from datetime import datetime
|
||||
import json
|
||||
from decimal import Decimal
|
||||
|
||||
# Re-using the custom encoder from the previous suggestion for robust date/decimal handling
|
||||
class CustomJSONEncoder(json.JSONEncoder):
|
||||
def default(self, obj):
|
||||
if isinstance(obj, datetime):
|
||||
return obj.isoformat()
|
||||
if isinstance(obj, Decimal):
|
||||
return str(obj)
|
||||
return json.JSONEncoder.default(self, obj)
|
||||
|
||||
def export_entry_with_author_details(request, entry_id):
|
||||
try:
|
||||
# 1. Get the LogbookEntry instance
|
||||
entry = LogbookEntry.objects.get(pk=entry_id)
|
||||
|
||||
# 2. Get the related PersonLogEntry and Person (Author)
|
||||
# Use .select_related() for efficiency
|
||||
author_link = PersonLogEntry.objects.select_related('person').get(
|
||||
entry=entry,
|
||||
is_author=True # Adjust filter based on your logic
|
||||
)
|
||||
author = author_link.person
|
||||
|
||||
except (LogbookEntry.DoesNotExist, PersonLogEntry.DoesNotExist):
|
||||
return HttpResponse(f'Entry or Author not found for ID {entry_id}', status=404)
|
||||
|
||||
# 3. Manually create the nested dictionary structure
|
||||
# Use model_to_dict for easy extraction of the simple fields
|
||||
|
||||
# Author data (specify fields you want to expose)
|
||||
author_data = model_to_dict(author, fields=['id', 'first_name', 'last_name', 'email'])
|
||||
|
||||
# Entry data (specify fields you want to expose)
|
||||
entry_data = model_to_dict(entry, fields=['id', 'title', 'content', 'date_created'])
|
||||
|
||||
# Nest the author data inside the entry data
|
||||
entry_data['author'] = author_data
|
||||
|
||||
# Add data from the intermediate model if needed (e.g., the date the person was added)
|
||||
entry_data['author_assignment_date'] = author_link.date_assigned.isoformat()
|
||||
|
||||
|
||||
# 4. Return the custom dictionary using JsonResponse
|
||||
return JsonResponse(
|
||||
entry_data,
|
||||
encoder=CustomJSONEncoder,
|
||||
safe=False # Set to True if entry_data was a list/QuerySet
|
||||
)
|
||||
Reference in New Issue
Block a user