我有一个抽象的Django模型,我用它来创建另外两个模型。在处理下面的不同示例时,如何避免重复代码(例如,在创建盒装谷物和Bowled
谷物时,我希望避免重复函数两次。你知道吗
class Cereal(models.Model):
name = models.CharField()
class Meta:
abstract = True
class Boxed(Cereal):
pass
class Bowled(Cereal):
pass
func some_func_boxed(name):
boxed = Boxed.objects.get(id=1)
boxed.name = name
boxed.save()
func some_func_bowled(name):
bowled = Bowled.objects.get(id=1)
bowled.name = name
bowled.save()
您可以将其添加为
@classmethod
模型上的Cereal
:然后,可以使用以下方法调用此方法:
调用class方法的类在
some_func_cereal
函数中作为cls
参数传递。你知道吗好主意是使用
strategy pattern
,例如:https://medium.com/@sheikhsajid/design-patterns-in-python-part-1-the-strategy-pattern-54b24897233e您可以将update方法添加到abstract类中,例如:
并按如下方式使用它来更新您喜欢的任何列
相关问题 更多 >
编程相关推荐