我一直很难在Django文档或类似的在线示例中找到关于如何最有效地查询以下模型的相关示例。
这些模型存储有关销售员工,团队,每周目标和实际生产的数据。
class Employee(models.Model):
employee_id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
email = models.EmailField()
status = models.CharField(max_length=100)
class Team(models.Model):
name = models.CharField(primary_key=True,max_length=100)
manager = models.ForeignKey(Employee, on_delete=models.CASCADE)
status = models.CharField(max_length=100)
start_date = models.DateField()
end_date = models.DateField()
class TeamMembers(models.Model):
team_name = models.ForeignKey(Team, on_delete=models.CASCADE)
employee_id = models.ForeignKey(Employee, on_delete=models.CASCADE)
status = models.CharField(max_length=100)
start_date = models.DateField()
end_date = models.DateField()
class Goal(models.Model):
employee_id = models.ForeignKey(Employee, on_delete=models.CASCADE)
goal = models.DecimalField(max_digits=6, decimal_places=2)
start_date = models.DateField()
end_date = models.DateField()
class Production(models.Model):
employee_id = models.ForeignKey(Employee, on_delete=models.CASCADE)
week = models.DateField()
quantify = models.DecimalField(max_digits=6, decimal_places=2)
根据提示的日期范围,我想显示一个页面,其中包含每个团队的表格,团队成员在该范围内(团队可以更改成员),以及他们的表现(目标可以每周更改)如下:
Time Period: 4/1/2018 - 4/28/2018
TEAM EAST Week 4/1 Week 4/7
Team Member Goal Actual Goal Actual
Joe 1000 1100 900 750
Mel 750 600 650 650
TEAM WEST Week 4/1 Week 4/7
Team Member Goal Actual Goal Actual
Kim 1000 1100 900 750
Pat 750 600 650 650
我倾向于首先在该日期范围内获得活跃的团队,然后循环通过团队以获得活跃的团队成员,然后循环通过团队成员获得他们的目标,在这些范围内生产,将所有这些存储在嵌套词典。但是大约有10个团队和100个团队成员,所以感觉就像是要进行大量的查询。
是否有更有效的方法可以将字典,成员,目标和制作放入字典中,以便用于显示数据?
谢谢!
答案 0 :(得分:0)
尝试简单的事情: 以下内容应该按照日期范围内的团队为您提供所有团队成员,您可以提前完成。使用select_related是重要的优化。我使用调试工具栏来检查性能。 更新到型号:
class TeamMembers(models.Model):
team_name = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='team_member_team_name')
Team.objects.filter(start_date='', end_date='').select_related('manager').prefetch_related(Prefetch('team_member_team_name', queryset=TeamMembers.objects.all().select_related('employee_id')))