使用Django执行POST操作后的计算

huangapple go评论50阅读模式
英文:

Calculation after POST action with Django

问题

我正在尝试使用Django Rest Framework创建一个用于计算效率的API。在将消耗和生产数值发送并保存到数据库后,我想对数据进行计算,找到效率并将其保存到数据库中。

我应该如何构建项目结构?我如何触发计算函数?你可以分享一个示例以帮助我吗?

英文:

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?

答案1

得分: 0

我不知道什么是效率计算,所以我只会告诉你在将数据保存到数据库后如何操纵数据。

Django有一个保存方法,每当实例在数据库中保存时都会触发,无论是新实例还是正在更新的实例,所以你可以简单地重写保存方法来操纵、读取、发送你想要的数据:

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: # 确保条目是新的,如果你也想在每次更新时进行计算,可以去掉这个条件
            self.valueMain = self.valueA + self.valueB # 在这里做任何你想做的事情
            self.save()

至于你的项目结构,这取决于整个系统,结构对你想要进行的计算影响不大。

英文:

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

huangapple
  • 本文由 发表于 2023年7月24日 20:05:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76754328.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定