2017-03-17 47 views
2

我在Employee和Manager類之間有繼承關係。 Employee - 超類,Manager - 子類。Django,Python繼承:從超類中排除一些字段

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) 
    ### 

怎麼能實現這個。提前致謝。

+0

即使這是可能的,這將使'經理'沒有名字。你確定你想要嗎? –

+0

在其他語言中,您可以將'Employee'' private'字段與'public'或'protected'字段相對應。 –

+0

爲什麼你不使用foreingkey? –

回答

3

您可以使用2個下劃線(__)在Python類中創建私有變量,請檢查this示例以獲取更多信息。

但是,他們會將該值存儲在子對象中,因爲在Python中沒有私有或受保護的東西。

但另一種方法可以爲Django工作。在Django模型字段將按照其價值(CharFieldDateField等)保存,但如果你將項目值None或任何其他靜態值(例如"string"),這應該解決您的問題:

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

在這個例子中,Manager不應該在數據庫中有名稱和地址列,當你嘗試訪問它們時,你會得到None。如果你想獲得AttributeError(Django的提高,當對象沒有請求的鍵),那麼你也可以添加屬性:

class Manager(Employee): 
    name = None 
    @property 
    def name(self): 
    raise AttributeError("'Manager' object has no attribute 'name'") 
4

我會使用3類:

class BaseEmployee(models.Model): 
    # All your common fields 

class Employee(BaseEmployee): 
    name = models.CharField(max_length=50, null=False) 
    address = models.CharField(max_length=50, null=False) 

class Manager(BaseEmployee): 
    department = models.CharField(max_length=50) 

我認爲,達到你想要的。