You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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:

Retrieve All Staff with Their Operating Hours

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}")

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:18:41