0

我是 django 和 python 的新手。我正在尝试找出进行查询的最佳(最高性能)方法。

这是我的模型:

class Immunization(models.Model):
    name = models.CharField(max_length=12, primary_key=True)
    verbose_name = models.CharField(max_length=80)
    desc = models.CharField(max_length=800)
    effective_duration = TimedeltaField()
    def __unicode__(self):
        return self.name

class Patient(models.Model):
    name = models.CharField(max_length=64)
    age = models.IntegerField()
    birthday = models.DateField()
    def __unicode__(self):
        return self.name

'''
    ImmunizationRecord is a specific date an immunization was administered to a given patient.
'''
class ImmunizationRecord(models.Model):
    patient = models.ForeignKey('Patient')
    immunization = models.ForeignKey('Immunization')
    date_administered = models.DateTimeField(auto_now_add=True)

我要执行的查询是:

*获取患者在过去 Immunizations.effective_duration 中未接受的所有免疫接种。*

到目前为止,我正在做这样的事情:

def get_context_data(self, **kwargs):
    context = super(ProfileView, self).get_context_data(**kwargs)

    all = Immunization.objects.all()
    done = ImmunizationRecord.objects.filter(patient__name=self.request.user)

    for r in done:
        #TODO: add date check for expiry
        all = [s for s in all if r.immunization.name != s.name] 

    context['available_list'] = all
    return context
4

2 回答 2

0

这样的事情可能会有所改善。

Import numpy
Import datetime 
recent_immunizations = ImmunizationRecord.objects.filter(patient=request.user).order_by(date_administered).reverse()


output = []
for r in recent_immunization:
   if (datetime.datetime.today() - r.date_administered) > r.immunizations.effective_duration:
       output.append(r.immunization.name)

Waring 此代码未经测试!

于 2013-11-12T05:05:31.027 回答
0

获取患者过去未接受的所有免疫接种 Immunizations.effective_duration

患者需要的所有疫苗接种。因此,如果他们在 20 天前接种了疫苗,并且有效持续时间 = 19,那么他们逾期 1 天,他们需要接种疫苗。

我们需要找一个病人;然后是他们接受的任何免疫接种。然后我们需要知道从今天起的天数和每次免疫接种的日期有什么不同;如果该差额小于有效天数;患者需要再次进行免疫接种。

import datetime

today = datetime.datetime.today()

p = Patient.objects.get(pk=1) # Get some patient
imm = ImmunizationRecord.objects.filter(patient=p) # This patient's record

still_needed = []

for record in imm:
   # How many days have passed since the immunization was administered?
   days_since = (today - record.date_administered).days

   if record.immunization.effective_duration < days_since:
      still_needed.append(record.immunization)
于 2013-11-12T05:19:30.107 回答