art.zhitnik
art.zhitnik

Reputation: 624

Class attribute inheritance in Django models

There are two models:

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

    class Meta:
        abstract = True

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

    def __init__(self, *args, **kwargs):
        super(BaseImage, self).__init__(*args, **kwargs)
        self.image.upload_to = 'images/news/%Y/%m/%d'

How can I set upload_to property in the base model? This my attempt doesn't work:

        self.image.upload_to = 'images/news/%Y/%m/%d'

Upvotes: 3

Views: 707

Answers (1)

Rohan
Rohan

Reputation: 53326

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)

Upvotes: 8

Related Questions