Search code examples
pythondjangoimagefield

How to defaultly return image.url when we get model Object?


I want my model object to always return the image.url of field image.

My model:

class Content(models.Model):
    ...
    avatar = models.ImageField(upload_to=file, blank=True, null=True)

I want something like:

class Content(models.Model):
    ...
    def get_avatar(self): # some default func for returning fields
        return self.avatar.url

It have to work like this, When I get the object:

content = Content.objects.get(pk=1)
print(content.avatar)

And it should print the path:

/media/uploads/dsadsadsa.jpg

Briefly, I want something that will change the return of model field.


Solution

  • You could add a property to your model like this, notice I added an underscore to the field name:

    class Content(models.Model):
        ...
        _avatar = models.ImageField(upload_to=file, blank=True, null=True)
    
        @property
        def avatar(self):
            return self._avatar.url
    

    Now you can do:

    print(content.avatar)