2017-03-06 52 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

請更新您的問題,而不是在評論張貼代碼 - 而更具體,「不工作」講述的是最沒用的可能問題描述。你也很想過濾當前病人的「考試」模型。 –