我是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
答案 0 :(得分: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此代码未经过测试!
答案 1 :(得分:0)
获取患者过去未接受的所有免疫接种
Immunizations.effective_duration
。患者需要的所有疫苗接种。所以,如果他们接种疫苗20 几天前,又有效_duration = 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)