How to stay dry with Django model field definitions

What is the best practice for following DRY rules when defining the fields of a Django model.

Scenario 1:

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

Can i do this:

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

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

How can I use file_one, _two and _three to inherit / extend the rules in base = models..., with the ability to assign to each otherpath=...

I feel like Django: defining a dynamic model region is close, but not quite what I'm looking for!

Excellent stack overflow!

+3
source share
2 answers

, . - , **. - :

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
)
+4

, DRY- , :) DRY zen 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!):)

+5

All Articles