[Django]-How to stay DRY with Django model field definitions

4👍

✅

I agree with Pete that you definitely don’t want to get too tricksy with a simple model definition. You could make the multiple nearly-the-same file fields a little easier to manage and still be explicit by keeping your defaults in a dictionary and using the ** operator. Something like:

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
)

5👍

Honestly, DRY code is important and should be strived for, but there are limits 🙂 In this case you’re at odds between DRY and line two of the zen of python Explicit is better than implicit. If I was maintaining your code I’d much rather come in and see:

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)

Because while not being “DRY”, it is immediately obvious what is going on, and I don’t have to waste time going “wait, what?”

(Actually strictly speaking what I’d like to see is:

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

.. but that’s because I’m a stickler for PEP8!) 🙂

Leave a comment