🎯Best Practices

A well-designed data model allows for a smooth development process and a source code that is easy to understand and maintain.

Model style

Models definition is one of the most important parts of our application. Something that makes all the difference in defining the field types properly.

Naming Models

The model definition is a class, so always use CapWords convention (no underscores). E.g. User, Permission, ContentType, etc

For the model’s attributes use snake_case. E.g. first_name, last_name, etc.

Always name your models using singular. Call it Subject instead of Subjects

from django.db import models

class Subject(models.Model):
    name = models.CharField(max_length=30)
    isbn_no = models.CharField(max_length=20)

Relationship Field Naming

For relationships such as ForeignKey, OneToOneKey, ManyToMany it is sometimes better to specify a name. Imagine there is a model called Article, - in which one of the relationships is ForeignKey for model User. If this field contains information about the author of the article, then author will be a more appropriate name than user.

triangle-exclamation

Do not use ForeignKey with unique=True

Attributes and Methods Order in a Model

The Django Coding Style suggests the following order of inner classes, methods, and attributes:

  • constants (for choices and others)

  • All database fields

  • Custom manager

  • class Meta

  • def __str__()

  • other special methods

  • def clean()

  • dev save()

  • def get_absolut_url()

  • other custom methods

If choices is defined for a given model field, define each choice as a list of tuples, with an all-uppercase name as a class attribute on the model.

Example:

For the "human-readable" value of a choice field, use get_FOO_display()arrow-up-right.

Reverse Relationships

The related_name attribute in the ForeignKey fields are extremely useful. It lets us define a meaningful name for the reverse relationship.

Rule of thumb: if you are not sure what would be the related_name, use the plural of the model holding the ForeignKey.

That means the Company model will have a special attribute named employees, which will return a QuerySet with all employees instances related to the company.

related_query_name

This kind of relationship also applies to query filters. For example, if I wanted to list all companies that employ people named ‘Santosh’, I could do the following:

If you want to customize the name of this relationship, here is how we do it:

In Student Models

To use it consistently, related_name goes as plural and related_query_name goes as singular.

Meta class

The Meta classarrow-up-right is incredibly powerful and has a long list of featuresarrow-up-right.

A good first step is to explicitly name your model too, not just your fields. This can be done with verbose_name and verbose_name_plural. Otherwise, Django would just add ansto make it pluraluniversitys which is wrong.

Be aware though that there can be a performance hit to ordering resultsarrow-up-right so don't order results if you don't need to.

triangle-exclamation

Do not use null=True or

circle-check

Business logic is in the model method and model manager.

Field Duplication in ModelForm

🚫 Do not duplicate model fields in ModelForm or ModelSerializer without need. If you want to specify that the form uses all model fields, use MetaFields. If you need to redefine a widget for a field with nothing else to be changed in this field, make use of Meta widgets to indicate widgets.

triangle-exclamation

Do not use objectDoesNotExist

triangle-exclamation

Do not add an extra .all() before filter(), count() etc.

Many flags in a model?

replace several BooleanFields with one field, status

Redundant model name in a field name

Do not add model names to fields if there is no need to do so, e.g. if the table User has a field user_status - you should rename the field into status, as long as there are no other statuses in this model.

circle-check

Getting the earliest/latest object

we can use ModelName.objects.earliest('created'/'earliest') instead of order_by('created')[0] and we can also put get_latest_by in Meta model. We should keep in mind that latest/earliest as well as get can cause an exception DoesNotExist. Therefore, order_by('created').first() is the most useful variant.

triangle-exclamation

Never use len(queryset)

triangle-exclamation

if queryset is a bad idea

triangle-exclamation

Do not use FloatField to Store Money Information

Don't use null=true if you don't need it

Avoid using nullarrow-up-right on string-based fields such as CharFieldarrow-up-right and TextFieldarrow-up-right. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL.

null=True - It is database-related. Defines if a given database column will accept null values or not. blank=True - It is validation-related. It will be used during forms validation when callingform.is_valid(). In TextField it's better to keep the default value. blank=True , default=''

Transparent fields list

Do not use Meta.exclude for a model’s fields list description in ModelForm. It is better to use Meta.fields for this as it makes the fields list transparent.

Do not heap all files loaded by the user in the same folder

Sometimes even a separate folder for each FileField will not be enough if a large amount of downloaded files is expected. Storing many files in one folder means the file system will search for the needed file more slowly.

Use abstract models

If we want to share some logic between models, we can use abstract models.

Use custom Manager and QuerySet

The bigger the project we work on, the more we repeat the same code in different places.

To keep our code DRY and allocate business logic in models, we can use custom Managers and Queryset.

For example. If you need to get comments to count for posts, from the example above.

If we want to use this method in the chain with others queryset methods, we should use custom QuerySet:

circle-check

Some Tips

Resources

Last updated