[Answered ]-How to create property methods in django models dynamically?

1👍

Use mixins.

class ImageUrlMixin:

    @property
    def image_url(self):
        if self.image and hasattr(self.image, "url"):
            return self.image.url

class FileUrlMixin:

    @property
    def file_url(self):
        if self.file and hasattr(self.file, "url"):
            return self.file.url

class FileImageUrlMixin(FileUrlMixin, ImageUrlMixin):
    pass

class OnlyHasFileFieldModel(FileUrlMixin, models.Model):
    # ..model implementation

class OnlyHasImageFieldModel(ImageUrlMixin, models.Model):
    # ..model implementation

class HasBothFileAndImageFieldModel(FileImageUrlMixin, models.Model):
    # ..model implementation

Or if you want to support fields dynamically e.g. my_model.arbitrary_field_url:

class DynamicFieldUrlMixin:

    def __getattr__(self, name):
        if name.endswith("_url"):
            field_name = "".join(name.split("_")[:-1])
            field = getattr(self, field_name, None)
            if hasattr(field, "url"):
                return field.url
        raise AttributeError

Leave a comment