简体   繁体   中英

Calculating fields with filters in Django

I am extremely new to Django and kinda new to python and programming in general, so i may be asking a dumb question. I am trying to track medications in our inventory at work. Here is my model for the inventory in our safe

class Safe(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    date_created = models.DateTimeField(auto_now=True)
    drug_name = models.ForeignKey('components.Drug', related_name='drug_remove', on_delete=models.PROTECT, default=0)
    amount_removed = models.IntegerField(blank=True, null=True)
    amount_added = models.IntegerField(blank=True, null=True)
    incident_number = models.CharField(max_length=20, default=0, blank=True)
    patient_name = models.CharField(max_length=20, default=0, blank=True)
    medic_unit = models.ForeignKey('components.MedicUnit', related_name='medic_unit', on_delete=models.PROTECT, blank=True)
    free_text = models.CharField(max_length=1000, default=0, blank =True)
    drug_total = computed_property.ComputedIntegerField(compute_from='add_drug')

I would like to store the medication total for each drug in the database. I understand from researching this that storing totals isn't best practice in most cases but I believe this is one exception. Obviously the calculated integer field isn't the answer, but none of my research has gotten me any closer to the answer. My guess is that I first need to filter by 'drug_name' and then calculate the added or subtracted drugs from the previous total in a function within my model. Thanks ahead of time for any help.

I might be getting wrongly what you need. But it seems to me that you just need to compute the drug_total + drug_added - drug_removed is that correct? Add this to the bottom of your model:

def get_current_amount_of_drug(self):
    return self.drug_total - self.drug_removed + self.drug_added

Then from any view or other place where you need it - you can just call

safe = Safe.objects.filter(drug_name="My Drug").first() # or however you filter them and then just get
safe.get_current_amount_of_drug()

Maybe the documentation would help you more: https://docs.djangoproject.com/en/2.2/topics/db/models/#model-methods

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM