【问题标题】:How to stay DRY with Django model field definitions如何使用 Django 模型字段定义保持 DRY
【发布时间】:2014-03-08 22:10:09
【问题描述】:

在定义 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()

我可以这样做吗:

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 很接近,但不是我想要的!

保持令人敬畏的堆栈溢出!

【问题讨论】:

    标签: python django django-models models dry


    【解决方案1】:

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

    因为虽然不是“DRY”,但发生了什么立即显而易见,我不必浪费时间去“等待,什么?”

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

    # 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 的忠实拥护者!):)

    【讨论】:

    • 哲学+1,但自从基普回答了我的问题......:p
    【解决方案2】:

    我同意 Pete 的观点,您绝对不想让简单的模型定义变得过于棘手。通过将默认值保存在字典中并使用 ** 运算符,您可以使多个几乎相同的文件字段更易于管理并且仍然是明确的。比如:

    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
    )
    

    【讨论】:

    • +1 表示建议,U+2713 表示回答我的问题 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2010-11-08
    • 2013-07-15
    • 2012-03-17
    • 2019-03-16
    相关资源
    最近更新 更多