【问题标题】:Django and computed fields in a legacy database遗留数据库中的 Django 和计算字段
【发布时间】:2011-10-26 09:17:53
【问题描述】:

我正在逐渐用基于 django 的系统替换遗留的数据库前端。所有模型都是 Managed = False,以保留原始 db 结构。

但是,我遇到了计算表中的字段的问题。该字段在(伪)sql 中定义为 full_name = fname|| ||lname.

我可以将 full_name 字段定义为字符字段;我可以毫无问题地阅读它,但是任何更新记录的尝试都会导致该字段出现更新错误。

我可以使用@property;但这复制了 django 中的功能,而不是显示来自 db 本身的结果。使用这种方法会导致使用 UDF 定义的更复杂的字段(在我尚未到达的表中)出现问题。

真正需要的是模型本身的“只读”或“计算”属性;实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: django models readonly


    【解决方案1】:

    你只是想在你的类中定义一个方法吗?比如:

    def Person(models.Model):
      fname=models.CharField(...)
      lname=models.CharField(...)
    
      def fullname(self):
         return self.fname+" "+self.lname
    

    (不完全确定 Managed=False 是什么意思...)

    【讨论】:

    • 嗯...这可行,但它会从 python 代码生成答案。这在我上面使用的示例中很好,但它不会包含通过为 DB 编写的 C++ 库(UDF 或“用户定义的函数”)填充的更复杂的字段。 Managed = False 阻止对模型定义的任何更改更改数据库表,顺便说一句... /p
    • 您可能必须编写一些方法(如我的全名)来构建相关的 SQL 并执行它 - 有关本机 SQL 执行的详细信息在 django 文档中。所以它不会是任何类型的 xxxField。
    • 也许我的问题并不清楚......如果我将它定义为正确的类型,我在检索值时没有问题;但是,如果我这样做,模型希望能够更新它不能这样做的字段,因为它是由数据库本身计算的字段。因此需要告诉模型,“您可以选择此字段,但不能插入或更新它” - 并从生成的 sql 中删除该字段。
    【解决方案2】:
      if you are trying to make calculation on a database models and pass the value of a model field to another model field of the same class model, using a defined function then this solution might help you. for example lets assume you have an investment company and you give 20% per month for the capital each user invested, you would want  want to pass value from capital model to a function that calculates the percentage interest, and then you will pass that function into another field monthly_payment and get saved in the database. 
        1) pip install django-computed-property 
        2) add 'computed_property' to your installed apps in project settings. 
        3) in your models.py, import computed_property then
    

    类投资(models.Model):

        name = models.CharField(max_length=200)
        capital = models.FloatField(null=False)
    
        percentage = models.CharField(max_length=5)
        duration = models.CharField(max_length=10, default="1 months")
    
        monthly_payment = computed_property.ComputedFloatField( compute_from='monthly_percentage', null=False, blank=False)
    
    then your function to perform the calculation will go thus 
        @property
        def monthly_percentage(self):
            return (20 / 100) * self.capital 
    

    注意:我发现如果您使用内置的 django 字段,无论是 FloatFiled 还是 IntegerField,此函数将不会读取您传入的数量以进行 20% 的计算。我希望这对您有用,正如我所说他们为我工作,干杯。

    【讨论】:

      猜你喜欢
      • 2011-11-21
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多