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.
- Explicitly name your model, not just your fields. For this, you would use
verbose_name
andverbose_name_plural
(Django would just add ans
to make it plural,citys
, which is not correct)
|
|
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”- 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.