[Django] #33944: Is it cleaner to make the upload_to function a method of the model class

7 views
Skip to first unread message

Django

unread,
Aug 20, 2022, 5:56:05 PM8/20/22
to django-...@googlegroups.com
#33944: Is it cleaner to make the upload_to function a method of the model class
--------------------------------------------+------------------------
Reporter: Willem Van Onsem | Owner: nobody
Type: New feature | Status: new
Component: Documentation | Version: dev
Severity: Normal | Keywords:
Triage Stage: Unreviewed | Has patch: 0
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
--------------------------------------------+------------------------
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.

--
Ticket URL: <https://code.djangoproject.com/ticket/33944>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

Django

unread,
Aug 22, 2022, 3:37:57 AM8/22/22
to django-...@googlegroups.com
#33944: Is it cleaner to make the upload_to function a method of the model class
----------------------------------+--------------------------------------

Reporter: Willem Van Onsem | Owner: nobody
Type: New feature | Status: closed
Component: Documentation | Version: dev
Severity: Normal | Resolution: invalid

Keywords: | Triage Stage: Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
----------------------------------+--------------------------------------
Changes (by Carlton Gibson):

* status: new => closed
* resolution: => invalid


Comment:

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

--
Ticket URL: <https://code.djangoproject.com/ticket/33944#comment:1>

Reply all
Reply to author
Forward
0 new messages