【问题标题】:Django- Staying DRY with multiple model methodsDjango- 使用多种模型方法保持 DRY
【发布时间】:2015-06-18 11:38:15
【问题描述】:

在使用需要其他模型方法结果的模型方法时,保持 DRY 的首选方法是什么?

例如:

class MyModel(models.Model):
    a = models.IntegerField()
    b = models.IntegerField()
    c = models.IntegerField()

def _method_one(self):
    x = a + b    
    return x    
    method_one = property(_method_one)

def _method_two(self):
    x = a + b
    y = x + c
    return y
    method_two = property(_method_two)

def _method_three(self):
    x = a + b
    y = x + c
    z = x + y
    return z
    method_three = property(_method_three)

随着越来越多的方法依赖于以前的解决方案,我最终会重复代码。处理这个问题的最干净的方法是什么?

提前致谢。

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    为什么不直接做:

    class MyModel(models.Model):
        a = models.IntegerField(default=0)
        b = models.IntegerField(default=0)
        c = models.IntegerField(default=0)
    
        @property
        def x(self):
            return self.a + self.b
    
        @property
        def y(self):
            return self.x + self.c
    
        @property
        def z(self):
            return self.x + self.y
    

    【讨论】:

    • 谢谢!我很早就尝试过,但由于某种原因它对我不起作用。我一定是做错了什么,但这就像我预期的那样工作。
    • 字段的默认值很重要,否则会出错。始终进行防御性编码,即使是针对自己 :)
    • 很高兴知道!我将开始在我的模型上实现它们。感谢您的帮助!
    猜你喜欢
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    相关资源
    最近更新 更多