[Django]-Class attribute inheritance in Django models

8👍

✅

What I can suggest is to write function to get upload to method from instance e.g.

in models.py

#default method to get file upload path
def get_upload_to(instance, filename):
    return instance.get_upload_to_path(filename)

class BaseImage(models.Model):
    description = models.CharField(max_length=200)
    image = models.ImageField(upload_to=get_upload_to)

    class Meta:
        abstract = True
    #method on the class to provide upload path for files specific to these objects
    def get_upload_to_path(instance, filename):
         return 'images/'+filename

class PostImage(BaseImage):
    in_text = models.BooleanField()

    #method to provide upload path for PostImage objects
    def get_upload_to_path(instance, filename):
    #change date.year etc to appropriate variables
         return 'images/news/%Y/%m/%d' % (date.year, date.month, date.day)

Leave a comment