如果问题的标题不正确,请道歉。请有人纠正它,如果这里的细节让你知道我要什么。我不会说英语,所以可能会在标题的措辞上出错
我有这个模型:
class ClinicDoctor(models.Model):
doctor = models.ForeignKey('User', related_name='doctorsF') # single quotes (') because User table is defined down the code.
clinic = models.ForeignKey(Clinic, related_name='clinicsF')
我正在找所有的医生病历和他们的诊所。有些医生可能有多个诊所。在我的模板中,我循环使用以下查询集:
doctorsQuerySet = ClinicDoctor.objects.filter(doctor__groups__name='Doctor')
这将返回记录,但我想在如下表中显示记录:
医生头--------临床医生头
医生1---------------诊所1,诊所2。
医生2------------诊所3
医生3---------------诊所4、诊所5、诊所7
我的想法是,我只想给每个医生看一次,然后把他所有相关的诊所放在医生的那一排
现在我正在循环模板中的查询集,但它将多次显示同一个医生记录(与相关诊所的数量相同)
有没有什么方法可以让我修改上面的查询来实现分组,或者我必须在模板中处理它,以查看医生id何时从以前的循环运行中更改并连接诊所,然后将它们放在<td>
标记中
我试着搜索,但没有找到与我的情况相关的问题。可能是我搜索时的措辞和我要找的不一样。如果已经有人解决了,我道歉。你可以分享这个链接
谢谢你
如果您只需要模板中的数据,可以使用以下代码(请注意,下面的代码实际上并没有经过测试,但希望能让您朝着正确的方向前进):
视图.py
模板.html
首先将您的医生查询传递到模板,然后在模板上循环。
clinicdoctor_set.all
将检索该医生的所有ClinicDoctor条目(_set.all
允许您反向检索外键关系中的所有条目)。然后可以正常引用关联的外键{% if not forloop.last %}, {% endif %}
将在每个clinic条目之间添加逗号,循环的最后一个条目除外您可以在Related objects reference和Template reference下阅读更多关于这方面的内容
相关问题 更多 >
编程相关推荐