In Django, properly defining database models is arguably the most important part of a new project. It is however very flexible in how we structure our models.

Official Django coding style recommends following order:

  • choices
  • database fields
  • custom manager attributes
  • Meta
  • def __str__()
  • def save()
  • def get_absolute_url()
  • custom methods

Today I want to look at some good practices I have learned so far regarding the Meta class.

  1. Explicitly name your model, not just your fields. For this, you would use verbose_name and verbose_name_plural (Django would just add an s to make it plural, citys, which is not correct)
1
2
3
class Meta:
	verbose_name = 'city'
	verbose_name_plural = 'cities'
  1. ordering is also very common - it defines the default order of a list of objects - however, ordering can be a performance hit, so as Django’s documentation says - “Don’t order results if you don’t care”
  2. If you do care, and want to use ordering, it is also a good idea to use indexing

The Meta class is very powerful and there is of course a lot more, but these are just some options I have used recently.