Reputation: 145
I have a Photo-Model that helps me achieve storing each image as a thumbnail aswell:
class Photo(models.Model):
image = models.ImageField(upload_to=upload_path, default=default_image)
thumbnail = models.ImageField(upload_to=upload_path_2, editable=False, default=default_image_2)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class Meta:
abstract = True
Now I have another Model, lets call it User, which inherits from Photo:
class User(Photo):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
Now lets say there are multiple classes inheriting from Photo and depending on the inheriting class, I want to set another upload_path and default_image. How Do I achieve that? Can I somehow use the constructor?
Thanks in Advance!
Upvotes: 1
Views: 75
Reputation: 5888
I'd say that the best way to handle your use-case is slightly different. You can pass a function to upload_to
. This function will be provided the signature instance
and filename
of the uploaded file (docs).
You can check class of the instance with isinstance
or something similar and change the output accordingly.
def upload_path(instance, filename):
if isinstance(instance, User):
return 'user_{0}/{1}'.format(instance.user.id, filename)
return 'photo/{1}'.format(filename)
Doing the same for default
is a little bit harder. The default
function won't be passed any reference to the model or field which will make it harder to override it based on model. You could simply add an image
field to each of the concrete models, but I don't know if that would be appropriate.
Upvotes: 1