如何在Django中从关联表获取数据?请求获取员工及对应工作时间
Hey there! Let's get you all the staff information along with their corresponding operating hours. Based on your Django models, here are a few practical approaches to achieve this:
1. Basic Query (Simple but May Cause N+1 Issues)
You can first fetch all staff members, then iterate through each to access their related operating hours via the days related name:
# Fetch all staff records all_staff = Staff.objects.all() # Loop through each staff and display their details + hours for staff in all_staff: print(f"Staff: {staff.name} {staff.last_name}") print("Operating Hours:") for hours_entry in staff.days.all(): # Convert day integer to readable name using your constants day_label = dict(constants.DAYS).get(hours_entry.day, "Unknown Day") print(f"- {day_label}: {hours_entry.start_time} to {hours_entry.end_time}")
2. Optimized Query (Avoid N+1 with Prefetch Related)
If you have a large number of staff members, using prefetch_related is better—it fetches all related operating hours in a single additional query, boosting performance:
# Prefetch all related operating hours upfront all_staff = Staff.objects.prefetch_related('days').all() # Same iteration logic as above, but with fewer database hits for staff in all_staff: print(f"Staff: {staff.name} {staff.last_name}") print("Operating Hours:") for hours_entry in staff.days.all(): day_label = dict(constants.DAYS).get(hours_entry.day, "Unknown Day") print(f"- {day_label}: {hours_entry.start_time} to {hours_entry.end_time}")
3. Filtered Operating Hours (Optional)
If you only need specific subsets of hours (e.g., weekday hours), use Prefetch to filter the related records during fetch:
from django.db.models import Prefetch # Define your filtered queryset (adjust day values to match your constants) weekday_hours = OperatingHours_staff.objects.filter(day__in=[1, 2, 3, 4, 5]) # Prefetch only the filtered hours, stored under a custom attribute all_staff = Staff.objects.prefetch_related( Prefetch('days', queryset=weekday_hours, to_attr='weekday_days') ).all() # Access the filtered hours for staff in all_staff: print(f"Staff: {staff.name} {staff.last_name}") print("Weekday Operating Hours:") for hours_entry in staff.weekday_days: day_label = dict(constants.DAYS).get(hours_entry.day, "Unknown Day") print(f"- {day_label}: {hours_entry.start_time} to {hours_entry.end_time}")
Hope this helps you get exactly the data you need! 😊
内容的提问来源于stack exchange,提问作者pratik veer

