So i was learning about customizing the user model in Django and found two options to do it:
One option is to use inheritance to extend the user
model (abstract user class), so we can create another model called AppUser
and this model should extend the user
model (abstract user class) in Django.
The other option is to create a profile, so we can create a Profile
model and in this model we will add a one to one link with the user
model, so in this scenario we are not using inheritance, we are using composition. So the Profile model is composed of a user model.
In terms of the database with the first approach we will end up extending the user
table (abstract user class), so any extra attributes that we add in our custom user model will end up in this table.
In the first approach how is it that adding extra attributes in the custom user model are ending up in the same table ? According to OOP if we you add any attributes to the child class shouldn’t they only be available in the child class only, not in the parent class.
I asked ChatGPT about it and it gave me this output:
In regular Python, when you define a child class that inherits from a parent class, the child class has access to the attributes and methods of the parent class, but those attributes are not stored in the same table or structure in memory.
The behavior you mentioned, where fields from both parent and child classes are stored in the same table, is specific to Django's implementation of model inheritance, especially when using multi-table inheritance.
In Django's ORM (Object-Relational Mapping), when you use multi-table inheritance with model classes, Django creates a separate table for each class, and each table includes fields from both the parent and child classes. This allows Django to support querying and fetching data across both the parent and child models in a more efficient manner.
So, while the behavior might seem different from standard Python inheritance, it's a design choice made by Django to facilitate working with databases and querying related data efficiently. It's important to understand this distinction when working with Django models and inheritance. In regular Python classes, the child class does not affect the structure of the parent class, and each class has its own separate attributes.
Is it correct because i don’t fully trust it ?
I am a CSE student so sorry if my question are not up to the mark or too basic but i think this is the best place to learn about this framework and thank you in advance.