Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, Python inheritance: Exclude some fields from superclass

I have inheritance between Employee and Manager classes. Employee - superclass, Manager - subclass.

class Employee(models.Model):
    name = models.CharField(max_length=50, null=False)
    address = models.CharField(max_length=50, null=False)
    
class Manager(Employee):
    department = models.CharField(max_length=50)
    """
    Here I don't want the 'name' and 'address' fields of Employee class.
    (I want other fields of Employee and 'department' field of this 
    class to be stored in Manager table in database)
    """

How can achieve this. Thanks in advance.

like image 797
Kholdarbekov Avatar asked Mar 17 '17 14:03

Kholdarbekov


1 Answers

You can make private variables in python class using 2 underscores (__), check this example for more.

However they will store that values in child object as there is no such thing as private or protected in Python.

But another approach can work for Django. In Django model fields are stored depending on their value (CharField, DateField and etc.) but if you will make item value None or any other static value (ex. "string"), that should solve your problem:

class Manager(Employee):
  name = None
  address = None
  # other_stuffs.

In that example, Manager should not have name and address columns in database and when you will try to access them, you will get None. And if you want to get AttributeError (Django raises that when object hasn't requested key) then you can also add property:

class Manager(Employee):
  name = None
  @property
  def name(self):
    raise AttributeError("'Manager' object has no attribute 'name'")
like image 76
Emin Mastizada Avatar answered Oct 06 '22 01:10

Emin Mastizada