Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculation after POST action with Django

I am trying to create an API for efficiency calculation using Django Rest Framework. After sending and saving the consumption and production values to the database, I want to perform calculations on the data and find the efficiency and save it to database.

How should I structure the project? How can I trigger the calculation function? Could you share an example that can help with this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I don’t know what efficiency calculation is so i’ll just tell you how you can manipulate data after saving to your database

django has a save method that fires everytime an instance is saved in the DB new instance or an instance that is being updated, so you can simply override the save method to manipulate, read, send your data how ever you want:

class YourModel():
    valueA = models.IntegerField()
    valueB = models.IntegerField()
    valueMain = models.IntegerField()


    class Meta:
         pass

    def save(self, *args, **kwargs):
        is_new_instance = not self.pk
        super().save(*args, **kwargs)
        if is_new_instance: # making sure the entry is new, strip this if you want to do calculations on every update as well
            self.valueMain = self.valueA + self.valueB # do what ever you want here
            self.save()

as for your project structure that depends on the system as a whole the structure will have little impact on the calculation you want to do

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading