I'm new to both django and python. I'm trying to figure out the best (most performant) way to do a query.
Here is my models:
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)
The query I am trying to perform is:
* Get all Immunizations that a patient hasn't received in the past Immunizations.effective_duration.*
So far I am doing something like this:
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
Something like this might improve things a bit.
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 this code is not tested!
Get all Immunizations that a patient hasn't received in the past
Immunizations.effective_duration
.All vaccinations the patient NEEDS. So if they got the vaccination 20 days ago, and the effective_duration = 19, then they are 1 day overdue and they NEED the vaccination.
We need to get a patient; and then whatever immunization they have received. Then we need to know what is the difference in days from today and the date each immunization was administered; if that difference is less than the effective days; the patient needs that immunization again.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.