2017-03-06 74 views
0

型号:查询双外键和显示模板

class Patient(models.Model): 
patientID = models.CharField(max_length=200, unique=True, help_text='Insert PatientID') 
birth_date = models.DateField(auto_now=False, auto_now_add=False, help_text='YYYY-MM-DD') 
gender = models.CharField(max_length=200,choices=Gender_Choice, default='UNDEFINED') 

class Examination(models.Model): 
number_of_examination = models.IntegerField() 
patient = models.ForeignKey(Patient, on_delete=models.CASCADE) 
date_of_examination = models.DateField(auto_now=False, auto_now_add=False, help_text='YYYY-MM-DD') 

class GeneralData(models.Model): 
examination = models.ForeignKey(Examination, on_delete=models.CASCADE) 
height = models.FloatField(default='-', help_text= '[m] not [cm]! ') 
weight = models.FloatField(default='-', help_text= '[kg]') 
aha_classification = models.IntegerField(choices=AHA_CHOICES, default=0) 

我的问题: 我不知道如何与检查的数量= 1查询的通用数据对象为一个特殊的病人。我想在患者的详细信息页面上显示对象。我可以毫无问题地在考试课上进行查询。但是,我只是不知道如何查询generaldata对象。详细信息页面只加载Patient模型。由于这个原因,我必须从Patient模型中将检查模型查询到Generaldata模型吗?或者有可能在模板中加载其他模型?谢谢你的帮助!

Got it! 添加到我的DetailView:

def DetailView(generic.DetailView): 
model = Patient 
template_name = 'app/detail.html' 

    def get_context_data(self, **kwargs): 
    # Call the base implementation first to get a context 
    context = super(DetailView, self).get_context_data(**kwargs) 
    # Add in a QuerySet 
    context['FirstGeneral'] = GeneralData.objects.filter(examination__number_of_examination=1, examination__patient=get_object_or_404(Patient, pk=self.kwargs.get('pk'))) 
    return context 

回答

0

“的详细信息页面只加载患者模型(...)是有可能在模板中加载其他车型?”从您的视图代码,但实际上从最经常徘徊无论你想渲染 -

你不“负荷”模型“模板”,要将其传递(或任何你想要的其他对象)模板的context一个模板。当然,你可以通过任何你想要的,填充模板的上下文取决于你。

将工作查询: Generaldata.objects.filter(examination__number_of_examination=1, examination__patient=Testpatient)

但这是错误的顺序。

为什么“按错误顺序”?如果该查询起作用,阻止您使用它?

注:如果您使用的通用DetailView,增加额外的背景是documented here

+0

请更新您的问题,而不是在评论张贴代码 - 而更具体,“不工作”讲述的是最没用的可能问题描述。你也很想过滤当前病人的“考试”模型。 –