我有这两种方法,除了名称和一个变量之外,它们都是相同的,这确实让我烦恼,但无论我做什么,我都不知道如何实现它,以便我只需将一个变量传递到一个方法中在 Django 中。这是两种方法,如果需要,我可以发布模型,但我相当确定需要的所有信息都在这里,但为了清楚起见,这两个模型字段是“launch”、“staff_trials”和“published”所有三个都只是日期,所有其他变量都是在方法中创建的:
@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),因为不幸的是,这就是我仍在努力的地方。任何帮助以更好的方式重构此代码的帮助都将非常感激。我无法发布任何错误消息,因为错误消息太多,但它们都与 undefined variable 有关。
最佳答案
只需检查使用 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
关于python - 尝试将 DRY 原则应用于 django 中的建模方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61617512/