Models are Root of Django..!

Jamil Noyda
Analytics Vidhya
Published in
3 min readNov 3, 2019
source: internet ask for credit

You can’t build a great building on a weak foundation.Gordon B. Hinckley

Models are the foundation of ORM. With Django, you can boost your efficiency by 10x! in terms of complexity and promptness. But firstly, you have to understand how Django deals with the database!

While writing models, we often make mistakes since we are unaware of different ways of doing the same thing, probably the right one. Sometimes, due to lousy model design, it causes performance snag too. It is tough to solve this kind of snag since it requires structural changes, and we end up doing numerous migrations to make things up and running.

In this article, I will share some of my insight on model creation in Django.

The right relationship for the right thing!

One to one field relationship is used, when a record in the first table corresponds to only one record in the related table. E.g., the restaurant has only one place to serve meals. Right…?

And the restaurant has more than one waiter. In that case, we use ForeignKey, which is an example of one to many relationships!

A many-to-many relationship occurs when multiple records in a table are associated with various records in another table. For example, A pizza can have many toppings. And a topping can go on many pizzas. This is a great place to use a ManyToManyField.

Indexing Model!

Django will automatically create a B-Tree index on any foreign keys. They will be used in the where clause.

Asset.objects.filter(id=1)  # filtering on primary key properties
Asset.objects.filter(project__id=1) # filtering on foreign key properties with where clause

The models which are commonly used for searching and displaying, in that case, we can use indexing. E.g., the Product name(CharField) field requires indexing on its name field.

The example would be models.TextField(db_index = True)

and this will be used in filtering on column properties:Project.objects.filter(name__contains="Foo")

same goes with filtering on foreign key properties:

Asset.objects.filter(project__name__contains="Foo")

A good rule is if you are going to order by or filter by, it should be indexed. However, always remember, using indexing in a database has its costs, so use it wisely.

UniqueConstraint and CheckConstraint

These two constraints are used for validation on a model level, and it is one of the best practices to have validation on the model level.

Let’s look at an example, UniqueConstraint(fields=['room', 'date']) it ensures each room can only be booked once for each date; this solution is apt!

CheckConstraint does exactly what its name says, CheckConstraint(check=models.Q(age__ate=18) It will check the value before saving.

prefetch_related and select_related

prefetch_related use to prefetch the data from many to many & many to one relationships and to select the data from a single value relationship like one to one relationship. we do have select_related.

For example, you build a model and a model that has a relationship with other models. When a request comes, you will receive the query for their related data also. Django has excellent👌 mechanisms to access data from their relationship like book.author.name

But if you don’t use prefetchd_related and selected_related, Django creates a request to the database for every single relationship data. It causes performance snag😞. To overcome these difficulties, we have prefetchd_related and selected_related concepts😎.

Rules of Thumb👍

  1. Always Validate the field in a model level
  2. Queries should not be in loops
  3. Understand how the Queryset works
  4. The apt practice is to make Model methods. These Model instance will have access to all of its methods.

Examples: get_absolute_url(), __str__(), publish(), get_cost() get_info() calculate_total()

That’s all. Do you believe there could be other possible solutions? Do let me know in the comments below.

Django is a good web framework but I think, makes it good framework an ORM people😍

Conclusion

My conclusion is simple! Without a solid foundation, you’ll have trouble with anything of value. Models are a foundation of keys. First, work on it smartly and get it right eventually.

If you enjoyed this article, then hit the claps👏…!

Catch you later, keep coding and have fun ❤
Jamil.

--

--