Domanda

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!

È stato utile?

Soluzione 2

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
)

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top