Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stay DRY with Django model field definitions

What is the best practice for observing DRY principles while defining Django model fields.

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 have file_one, _two and _three inherit/extend the rules in base = models... while being able to assign each a different path=...

I feel like Django: Dynamic model field definition is close but not quite what I'm looking for!

Stay awesome Stack Overflow!

like image 708
Douglas Denhartog Avatar asked Dec 09 '25 22:12

Douglas Denhartog


1 Answers

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!) :)

like image 68
ptr Avatar answered Dec 11 '25 14:12

ptr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!