Dou*_*tog 3 python django dry django-models models
在定义Django模型字段时观察DRY原则的最佳实践是什么.
file_one = models.FilePathField(path=FIELD_PATH, allow_files=True, allow_folders=True, recursive=True)
file_two = models.FilePathField()
file_three = models.FilePathField()
Run Code Online (Sandbox Code Playgroud)
我可以这样做:
file_one = models.FilePathField(path=FIELD_PATH, allow_files=True, allow_folders=True, recursive=True)
file_two = file_one
...
Run Code Online (Sandbox Code Playgroud)
base = models.FilePathField(allow_files=True, allow_folders=True, recursive=True)
file_one = models.FilePathField(path=FIELD_PATH1)
file_two = models.FilePathField(path=FIELD_PATH2)
file_three = models.FilePathField(path=FIELD_PATH3)
Run Code Online (Sandbox Code Playgroud)
如何让file_one,_two和_three继承/扩展规则,base = models...同时能够为每个规则分配不同的path=...
我觉得像Django:动态模型字段定义很接近,但不是我想要的!
保持棒极了Stack Overflow!
老实说,DRY代码很重要,应该努力,但有限制:)在这种情况下,你在DRY和python的第二行之间存在分歧Explicit is better than implicit.如果我维护你的代码,我宁愿进来看看:
file_one = models.FilePathField(path=FIELD_PATH1, allow_files=True, allow_folders=True, recursive=True)
file_two = models.FilePathField(path=FIELD_PATH2, allow_files=True, allow_folders=True, recursive=True)
file_three = models.FilePathField(path=FIELD_PATH3, allow_files=True, allow_folders=True, recursive=True)
Run Code Online (Sandbox Code Playgroud)
因为虽然不是"干",但是很明显发生了什么,我不必浪费时间去"等,什么?"
(实际上严格来说,我希望看到的是:
# Useful comments
file_one = models.FilePathField(
path=FIELD_PATH1,
allow_files=True,
allow_folders=True,
recursive=True
)
# Useful comments
file_two = models.FilePathField(
path=FIELD_PATH2,
allow_files=True,
allow_folders=True,
recursive=True
)
Run Code Online (Sandbox Code Playgroud)
..但那是因为我是PEP8的坚持者!):)