2016-09-23 80 views
-1

好的實例化一個子類,現在我改變了我的模型如下:無法保存在我的Django模型

from django.contrib.auth.models import User 

class Company(User): 
    company_name = models.CharField(max_length = 20) 


class Employee(User): 
    pass 

當我從pytho運行manage.py殼下面的命令:

u = Employee(first_name = 'john', last_name = 'smith', password = 'test', email = '[email protected]') 
u.save() 
e = Employee(user = u) 
e.save() 

我得到以下錯誤,並不能真正理解爲什麼。 任何幫助表示讚賞,在此先感謝。

+2

請不要嘗試推倒重來,你應該關注如何創建你自己的用戶模型的djangos文檔 – Sayse

+0

找不到任何東西。任何參考? – roccoSenteta

+1

比Sayse走得更遠。您**不得**自行實施用戶驗證。 –

回答

0

書寫時:

class x(y) 

在Python,這意味着x延伸Y(從繼承)。

類Employee(用戶):
         通

讓人有點感(僱員是一個用戶),這

公司(用戶):

根本沒有意義(公司不是用戶)。

如果希望用戶將必須登錄爲公司的權利,我建議使用外鍵:

class Company(models.Model): 
    user_with_permissions_fk = models.ManyToManyField((User) 




至於這段代碼:

U =僱員(如first_name = '約翰',姓氏= '史密斯',密碼= '測試',電子郵件= '[email protected]')
u.save()
E = EM ployee(用戶= U)
e.save()

請提供你的語法錯誤 - 或者,請考慮使用此代碼替換:

new_records_to_insert = [] 
new_records_to_insert += Employee(first_name = 'john', last_name = 'smith', password = 'test', email = '[email protected]') 
new_records_to_insert += Employee(first_name = 'john', last_name = 'smith', password = 'test', email = '[email protected]') 
Employee.objects.bulk_create(new_records_to_insert) 
# No need to .save()