我正在尝试创建医生接受的保险计划清单,由计划提供者订购。如何构建一个允许我生成结果列表的查询:
Provider 1
Plan A
Plan B
Plan C
Provider 2
Plan D
Provider 3
Plan E
Plan F
给出以下(简化)模型:
class Provider(models.Model):
name = models.CharField(_('Name'), max_length=50)
class Plan(models.Model):
name = models.CharField(_('Name'), max_length=50)
provider = models.ForeignKey(Provider)
class DoctorProfile(UserProfile):
accepted_insurance_plans = models.ManyToManyField(Plan, blank=True)
答案 0 :(得分:2)
假设您正在寻求为给定的DoctorProfile生成此列表,dp:
import itertools
import operator
plans = Plan.objects.filter(doctorprofile=dp).\
order_by("provider").select_related("provider")
provider_plans = itertools.groupby(plans, operator.attrgetter("provider"))
然后,您可以按如下方式迭代按提供商分组的计划:
for provider, plan_group in provider_plans:
print provider.name
for plan in plan_group
print " %s"%plan.name
免责声明:我尚未测试此代码