pythondjangodjango-modelsdjango-3.0django-inheritance

Control object creation flow in Django inheritance models


I have been read some Django document about inheritance models and parent_link. Suppose that I have these models:

class Parent(models.Model):
    #Some field goes here! 
class Child(Parent):
    #Some field goes here! 

I have 3 questions about this pattern:

  1. What should I do if I want to create new child object and pass id of existing parent to that?

  2. What should I do if I want to create just new child object and after a while create parent object for that child?

  3. Also I din't understand this document about parent_link:

    OneToOneField.parent_link

    When True and used in a model which inherits from another concrete model, indicates that this field should be used as the link back to the parent class, rather than the extra OneToOneField which would normally be implicitly created by subclassing.

Thanks for your help!

Update Question Suppose these models:

class User(AbsteractBaseUser):
    #Some field goes here! 

class Student(User):
    #Some field goes here! 

class Teacher(User):
    #Some field goes here! 

class Employee(User):
    #Some field goes here! 
  1. Is it possible to create Teacher object and put the pk of existing User object for that teacher?

Solution

  • You cannot do that in Django ORM. Because if you think of database, it is possible but in OOP, it is not possible. So you should not use model inheritance in Django ORM. When you use inheritance, a foreign key to parent is created in child object in database but you cannot control it. You cannot change it or set it at the time of creation. If you see from database point of view, when you create child object, two objects are created in database i.e. one in parent and one in child. You should be able to assign another parent to this child object. But when you see OOP point of view, according to OOP principles, when a child is created, it inherits all the properties of parent and only one object is created. So do not have freedom to assign another parent object to this child.

    You can use abstract models instead. If you cannot remove inheritance, then you can do it with RAW SQL. Otherwise there is no any other option.

    If you can remove inheritance, create a OnetoOneField in child with parent.