Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An attempt to create a class naming style for django

Premise

Django code style is well documented however the documentation has no statement on how to name classes. When digging the documentation we can find various examples that does not follow an obvious standard.

Abstract base class documentation

from django.db import models

class CommonInfo(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()

    class Meta:
        abstract = True

class Student(CommonInfo):
    home_group = models.CharField(max_length=5)

Custom user model documentation

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass

Why AbstractUser has Abstract in the name but not CommonInfo? CommonInfo appears to be a bad example of an abstract model since it has two unrelated fields which makes it a trash bin of random fields. In this case maybe AbstractPerson would have been a better example for these fields and also it would be more consistent with real abstract models.

General rules

Concrete classes

  1. A concrete class must have maximum one explicit Abstract parent or another concrete class
  2. All other parents must be mixin-like classes

Naming django models

Django models are definitions of concepts we build our django your application onto (Ex: A Person, an User, an (auth) Token, etc.).

Typically we tend to name things with this kind of pattern <Concept><Design Pattern> (Ex:UserForm). However a model is the most real representation of a concept we can get in the application, for this reason we omit the Model suffix for concrete models (Ex: Person and not PersonModel).

General naming guidelines for naming models

Name Description Patterns Examples
Concrete model A concrete model that represents a concept. <ConcreteName> User Product
Abstract model An abstract model meant to become a concrete model directly Abstract<ConcreteName> AbstractUser AbstractProduct
Abstract base model Parent of an abstract model meant to be inherited from in order to customize its behaviours. AbstractBase<ConcreteName> AbstractBaseUser
Model mixin An abstract model meant to complement another model. Mixins for models <Adjective>Model TimeStampedModel OrderedModel
Base model mixin Parent of a complementary model meant to be inherited from in order to customize its behaviours. <Adjective>BaseModel <Adjective>ModelBase Base<Adjective>Model OrderedModelBase
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment