[英]How to add extra fields to a django model by extending it?
我正在使用Pinax Stripe開發一個django應用程序( https://github.com/pinax/pinax-stripe )。 Pinax條帶是一個捆綁的應用程序,它有一個名為'Plans'的模型。 現在在我的應用程序中,我想在我的應用程序BUT中為模型'Plans'添加一些額外的字段,而不修改原始的pinax條帶應用程序。
像這樣的東西:
#models.py
from pinax-stripe.models import Plan
class UserProfile(models.Model):
#write the extra fields here
有什么方法我可以做到然后用管理員注冊它所以我可以添加數據到管理面板中的這些字段?
您可以繼承Plan
模型並添加自己的屬性:
from pinax-stripe.models import Plan
class MyPlan(Plan):
# add your attributes
pass
這類似於python中的普通繼承,並且在運行遷移時會遷移自定義屬性,因為原始pinax Plan
是models.Model
的子類。
但是,請注意不要使用pinax Plan
模型中已存在的屬性名稱,因為新模型將自動從Plan
獲取所有屬性,而Django無法為重復字段編寫遷移。
您可以簡單地子類化Plan
並添加您想要的任何字段/方法:
from pinax-stripe.models import Plan
class UserProfile(Plan):
#write the extra fields here
我推薦你,使用像Django文檔建議在用戶模型中使用的OneToOne
關系
from pinax-stripe.models import Plan
class UserProfile(models.Model):
plan = models.OneToOneField(Plan , on_delete=models.CASCADE)
#write the extra fields here
您可以從https://github.com/pinax/pinax-stripe下載pinax文件夾到您的應用程序中,並根據您的要求編輯models.py和admin.py文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.