Opened 2 years ago

Closed 2 years ago

#33944 closed New feature (invalid)

Is it cleaner to make the upload_to function a method of the model class

Reported by: Willem Van Onsem Owned by: nobody
Component: Documentation Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

In the documentation of the upload_to field (https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to), it works with an example:

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)

class MyModel(models.Model):
    upload = models.FileField(upload_to=user_directory_path)

I'm wondering if this isn't more convenient by defining this as an instance method, so:

class MyModel(models.Model):
    def user_directory_path(self, filename):
        # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
        return 'user_{0}/{1}'.format(self.user.id, filename)
    upload = models.FileField(upload_to=user_directory_path)

Then the function can be used as a method, for example to just determine a file path without having to use it in the FileField per se. It also avoid defining all "standalone" functions that seem to be coupled to a model, and thus will make the models.py file less chaotic.

Change History (1)

comment:1 by Carlton Gibson, 2 years ago

Resolution: invalid
Status: newclosed

Hi Willem. I think you're likely free to do that, but I think questions such as this are better targeted at support channels. See TicketClosingReasons/UseSupportChannels.
(I don't think it's a change we need to enforce, or favour in the docs even.)

Note: See TracTickets for help on using tickets.
Back to Top