Note that there are some explanatory texts on larger screens.

plurals
  1. POPreferred pythonic way to associate upload_to function with model class?
    primarykey
    data
    text
    <p>I have a class with a <a href="https://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield" rel="nofollow noreferrer">Django ImageField</a> and I have been struggling to decide between two alternatives for storing that field's <code>upload_to</code> function. The first approach is pretty straightforward. The function is defined on the module level (c.f. <a href="https://stackoverflow.com/a/1190866/790075">https://stackoverflow.com/a/1190866/790075</a>, <a href="https://stackoverflow.com/a/3091864/790075">https://stackoverflow.com/a/3091864/790075</a>):</p> <pre><code>def get_car_photo_file_path(instance, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) # chance of collision &lt;1e-50 return os.path.join('uploads/cars/photos', filename) class CarPhoto(models.Model): photo = models.ImageField(upload_to=get_car_photo_file_path) </code></pre> <p>This is simple and easy to understand, but pollutes the module scope by adding a function that is really only pertinent to the CarPhoto class.</p> <p>In the second approach, I use the callable-class pattern to associate the function more closely with the CarPhoto class. This moves the <code>upload_to</code> function out of module scope but feels unnecessarily complicated.</p> <pre><code>class CarPhoto(models.Model): class getCarPhotoFilePath(): # Either use this pattern or associate function with module instead of this class def __call__(self, instance, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) # chance of collision &lt;1e-50 return os.path.join('uploads/cars/photos', filename) photo = models.ImageField(upload_to=getCarPhotoFilePath()) </code></pre> <p>I have seen suggestions for using the <code>@staticmethod</code> and <code>@classmethod</code> decorators (c.f. <a href="https://stackoverflow.com/a/9264153/790075">https://stackoverflow.com/a/9264153/790075</a>), but I find that when I do this the function never executes and the filename ends up looking like: <code>/path/to/file/&lt;classmethod object&gt;</code>, with the method object embedded in the file path, which is certainly not intended!</p> <p>Which of these is the preferred pattern? Is there a better way?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload