Naming properties and fields in Models

Sometimes in my models, beside a field I also need a property for the same model’s “attribute”.
The point is I’m struggling with the naming of fields vs properties - later when used in views or html code I’m not sure if it is property or field.

Is there a naming convention or a best practice how to name properties vs fields ?

For example, in the code below I have description / desc and image / img but I’m not so happy with this:

class Book(models.Model):
    description = models.TextField(...)
    welcome_image = models.ImageField(...)
    featured_image = models.ImageField(...)

    @property
    def desc(self):
        if not self.description:
            return "Something else..."
        return self.description

    @property
    def welcome_img(self):
        if not self.welcome_image:
            return self.featured_image
        return self.welcome_image

In my experience, the “common case” use of a property in a model is nothing more than syntactic sugar over what is effectively a getter function.

As a result, any properties we create are named with a get_ naming convention identifying the purpose for that property.

For example, in your first case (desc) it appears to exist to provide a default for those situations where description is null or blank. We might name that something like get_display_description.

1 Like