在视图中进行2种不同的搜索

时间:2013-08-31 19:49:34

标签: python django

我有两个表,一个存储医疗记录的信息,另一个存储第二个医疗咨询,我想要的是搜索,如果患者有第二次医疗咨询,请告诉我第二次医疗咨询的信息。我的模板,如果患者没有第二次医疗咨询,只会向我显示医疗记录的信息。 我需要有关如何做到这一点的帮助和想法,我是Django和Python的新手,我通过以下方式在视图中进行搜索,此搜索的问题是我只看到医疗记录,我需要如果患者进行了第二次医疗咨询以显示信息。

View.py

def Expediente_Detalle(request, credencial):
    Expediente_Detalle = get_object_or_404(ExpedienteConsultaInicial, credencial_consultainicial=credencial)
    return render(request, 'ExpedienteDetalle.html', {'Expediente_Detalle': Expediente_Detalle})

Models.py

class ExpedienteConsultaInicial(models.Model):       
    credencial_consultainicial = models.CharField(max_length=10, null=True, blank=True)

    def __unicode__(self):
        return self.credencial_consultainicial


class ConsultasSubsecuentes(models.Model):
     Consultasbc_credencial    =models.ForeignKey(ExpedienteConsultaInicial,
     related_name='csb_credencial')

2 个答案:

答案 0 :(得分:1)

尝试:

#Models

class ExpedienteConsultaInicial(models.Model):
    #max_legth=10 might be too small
    credencial_consultainicial = models.CharField(max_length=100, null=True, blank=True)

    def __unicode__(self):
        return self.credencial_consultainicial


class ConsultasSubsecuentes(models.Model):
     #related_name is name of attribute of instance of model 
     #to (not from!) which ForeignKey points.
     #Like:
     #assuming that `related_name` is 'consultations'
     #instance = ExpedienteConsultaInicial.objects.get(
     #                     credencial_consultainicial='text text text'
     #)
     #instaqnce.consultations.all()
     #So I suggest to change `related_name` to something that will explain what data of this model means in context of model to which it points with foreign key.
     consultasbc_credencial = models.ForeignKey(ExpedienteConsultaInicial,
     related_name='consultations')

#View    

def expediente_detalle(request, credencial):
    #Another suggestion is to not abuse CamelCase - look for PEP8
    #It is Python's code-style guide.
    detalle = get_object_or_404(ExpedienteConsultaInicial, credencial_consultainicial=credencial)
    subsequent_consultations = detalle.csb_credencial.all()
    return render(request, 'ExpedienteDetalle.html', {'Expediente_Detalle': detalle, 'consultations': subsequent_consultations})

有用的链接:

答案 1 :(得分:0)

您需要做的就是执行另一个查询,并将结果提供给您的模板

def Expediente_Detalle(request, credencial):
    Expediente_Detalle = get_object_or_404(ExpedienteConsultaInicial, credencial_consultainicial=credencial)
    second_consultation = ExpedienteConsultaInicial.objects.filter(..)
    return render(request, 'ExpedienteDetalle.html', {'Expediente_Detalle': Expediente_Detalle, 'second_consultation': second_consultation})

然后,在您的模板中,迭代second_consultation

{% for c in second_consultation %}
    <p> {{ c.credencial_consultainicial }} </p>
{% endfor %}