DEV Community

Discussion on: Using abstract models in Django

Collapse
 
ottohirr profile image
Otto Hirr

I find this to be a very bad example of using abstract base classes. Certainly it shows the repeated use of common fields from a base entity. Just because you can doesn't mean you should.

Per Django docs, there are different ways to inherent, this article only expresses one method.

The very heart of the article suggests DRY, yet the implementation fails that. A "teacher" could also be a "student" and a "student" could work part time as "cleaning staff" or "cafeteria staff", and so on.

For each case, the "teacher" would have a name, and other Person fields, and likewise the "student" would have a name and other Person fields - hence violating the very DRY reasoning for the article's depiction of inheritance.

A more accurate depiction of real world modeling would be to model a person and then add by relationship the various roles they may play.

Within Django, it would seem that given the concept of an app being a single full concept, a Person app would be a basis for modeling a real person. Then a different app for each of the other person roles would capture the additional fields and behavior associated with that particular role, all related, as an extension of a person.

Regards,

.. Otto

Collapse
 
kirancapoor94 profile image
Kiran Capoor

As per what I’ve observed, abstract models aren’t written in the DB. So there’s no Table for an abstract model.

The Django ORM, maps the fields to each model it’s subclassing only at the time of migrations.

However, when in the case of Inheritance, Django ORM fails miserably. N+1 queries, INNER JOINS are way too common which ultimately make the DB Queries VERY slow.

My recommendation is to use Abstract Tables only when needed, and avoid Inheritance completely when developing using Django. Instead use OneToOne/ForeignKey relationships to extend the tables.

Thanks 🍻

Collapse
 
guzmanojero profile image
guzmanojero

I don't follow what you're saying.

If an abstract model isn't creating tables you don't have a N+1 issue.

I've commented here:
dev.to/guzmanojero/comment/2ac2g

Can you expand?