Skip to content

[DJ12] Order of Model's inner classes, methods, and fields does not follow the Django Style Guide

Rocio Aramberri edited this page May 24, 2020 · 4 revisions

The Django Style Guide specifies that the order of Model inner classes, attributes and methods should be as follows:

  1. All database fields
  2. Custom manager attributes
  3. class Meta
  4. def __str__()
  5. def save()
  6. def get_absolute_url()
  7. Any custom methods

Don't

from django.db import models


class Post(models.Model):
    class Meta:
        verbose_name = 'post'

    title = models.CharField(max_length=150, null=True, blank=True)

    def custom_method(self):
        print("I should come after the save method")

    def save(self):
        super().save()

Do

from django.db import models


class Post(models.Model):
    title = models.CharField(max_length=150, null=True, blank=True)
    
    class Meta:
        verbose_name = 'post'

    def save(self):
        super().save()

    def custom_method(self):
        print("I should come after the save method")

References

https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/#model-style