2014-02-11 45 views
3

在定义Django模型字段时观察DRY原则的最佳做法是什么?如何使用Django模型字段定义保持DRY

方案1:

file_one = models.FilePathField(path=FIELD_PATH, allow_files=True, allow_folders=True, recursive=True) 
file_two = models.FilePathField() 
file_three = models.FilePathField() 

我可以这样做:

file_one = models.FilePathField(path=FIELD_PATH, allow_files=True, allow_folders=True, recursive=True) 
file_two = file_one 
... 

方案2:

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) 

如何我已经file_one,_TWO和_three继承/扩展规则在base = models...,同时能够分配不同的path=...

我觉得像Django: Dynamic model field definition是接近,但不是我所期待的!

保持真棒堆栈溢出!

回答

4

我与皮特同意你绝对不想在简单的模型定义中变得过于棘手。您可以使多个几乎相同的文件字段更易于管理,并且仍可以通过将默认值保存在字典中并使用**运算符进行显示。喜欢的东西:

filefield_defaults = { 
    'allow_files':True, 
    'allow_folders':True, 
    'recursive':True 
} 

file_one = models.FilePathField(
    path=FIELD_PATH1, 
    **filefield_defaults 
) 

file_two = models.FilePathField(
    path=FIELD_PATH2, 
    **filefield_defaults 
) 
+0

+1的意见,和U + 2713的答案,我的问题:) –

5

老实说,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) 

因为虽然不是“干”,这是显而易见这是怎么回事,我没有浪费时间去“等等,什么?”

(其实严格来说,我想看到的是:

# 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 
) 

..但是那是因为我是一个PEP8坚持己见):)

+0

+1的理念,但由于硖回答我的问题...:P –

相关问题