【问题标题】:trying to applying DRY principle to model methods in django尝试将 DRY 原理应用于 django 中的建模方法
【发布时间】:2020-05-05 15:59:52
【问题描述】:

我有这两种方法,除了名称和一个变量外,它是相同的,这真的让我很烦恼,但无论我做什么,我都无法弄清楚如何制作它,所以我只是将一个变量传递给一个方法在django。这是两种方法,如果需要,我可以发布模型,但我很确定所需的所有信息都在这里,但为了清楚起见,两个模型字段是“启动”、“员工试用”和“已发布”这三个都只是日期,所有其他变量都在方法中创建:

@property
def progress_launch(self):
    timeline = self.launch - self.published.date()
    current = self.launch - datetime.now().date()
    if timeline < current:
        percentage == 100
    else:
        percentage = 100 - round((current/timeline) * 100)
    min_bar = 1
    max_bar = 100
    if percentage is not None:
        if percentage < min_bar:
             return min_bar
        elif percentage > max_bar:
            return percentage
    else:
        percentage = max_bar
        return percentage

@property
def progress_trials(self):
    timeline = self.staff_trials - self.published.date()
    current = self.staff_trials - datetime.now().date()
    if timeline < current:
        percentage == 100
    else:
        percentage = 100 - round((current/timeline) * 100)
    min_bar = 1
    max_bar = 100
    if percentage is not None:
        if percentage < min_bar:
            return min_bar
        elif percentage > max_bar:
            return percentage
    else:
        percentage = max_bar
        return percentage

我尝试过这样做:

def progress_launch(self):    
    return percent(trials)

def progress_trials(self):
    return percent(launch)


def percent(_progress)
    timeline = _progress - self.published.date()
    current = _progress - datetime.now().date()
    if timeline < current:
        percentage == 100
    else:
        percentage = 100 - round((current/timeline) * 100)
    min_bar = 1
    max_bar = 100
    if percentage is not None:
        if percentage < min_bar:
            return min_bar
        elif percentage > max_bar:
            return percentage
    else:
        percentage = max_bar
        return percentage

当然它没有用。这两种方法效果很好,只是看起来很糟糕,而且这个特定的模型变得相当大。我很欣赏这更有可能是一个 OOP 问题(这就是为什么我首先开始学习 django 来学习 OOP),因为不幸的是,这就是我仍在苦苦挣扎的地方。非常感谢以更好的方式重构此代码的任何帮助。我无法发布任何错误消息,因为它们太多了,但它们都是关于未定义的变量。

【问题讨论】:

    标签: python django oop django-models


    【解决方案1】:

    只需检查您使用isinstance 获得的模型并使用适当的字段:

    @property
    def progress(self):
        if isinstance(self, LaunchModel):
            start = self.launch
        else:
            start = self.staff_trials
        timeline = start - self.published.date()
        current = start - datetime.now().date()
        # ... etc 
    

    你可以把它压缩成一行:

    start = self.launch if isinstance(self, LaunchModel) else self.staff_trials
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多