Django Abstract Models vs Simple Python mixins vs Python ABCs

This is a question raised by another question from me.

Django provides abstract base classes (which are not the same as the ABC classes in Python?) So that you can create a model (Django models.Model) from which you can inherit, but without this model having the actual table in the database. One causes this behavior by setting the abstract attribute in the Meta Model class.

Now the question is: why does Django allow it this way? Why is this special type of model of an abstract base class needed? Why not create a model mix by simply inheriting from the class of an object and mixing it with an existing model? Or could it also be a task for Python ABC? (note, I'm not very familiar with ABC classes in Python, my ignorance can show here)

+9
python django
Jul 16 '10 at 9:11
source share
2 answers

I will try to be brief enough, as this can easily turn into a long diatribe:

There are no ABCs because they were introduced only in Python 2.6, and Django developers have a roadmap installed to support the Python version (support for 2.3 was reset only in version 1.2).

As for object-inherited mixins, they will be less Pythonic to a greater extent than just decreasing readability. Django uses a metaclass ModelBase for Model objects, which actually analyzes certain properties of the model during initialization and populates Model._meta fields, Meta parameters, and other properties. It makes sense to reuse this structure for both types of models. It also allows Django to prevent overriding the abstract fields of models by inheriting models.

There are many more reasons that I can think of, they are all insignificant in themselves, but they add to make the current implementation much more Pythonic. However, there is nothing wrong with using object-inherited mixins.

+11
Jul 16 '10 at 13:38
source share

One reason is related to how fields are defined on the model.

Fields are declared declaratively so that the normal class is considered as class attributes. However, they must become attributes of the instance when the class is actually created, so that each instance can have its own value for each field. Management is through a metaclass. This will not work with a normal abstract base class.

+6
Jul 16 '10 at 13:56
source share



All Articles