[英]Correct way to add fields to a model on django
我有一個用戶模型,我想在數據庫和用戶表單中向用戶添加一個新字段。 我已經在網上查看了許多不同的方法來執行此操作,但是我想知道什么是“正確”的方法。 特別是創建遷移的正確方法。
Django版本:(1,10,0,u'final',1)
不確定我是否找到了您想要的東西,但是假設您要向“用戶”模型中添加“狀態”字段,然后將其放入“管理”面板中,以便可以與它進行交互(更新,更改等)。 )。
在models.py中-我們正在創建一個Profile類,該類將鏈接到User,然后將狀態添加到用戶:
class Profile(models.Model):
" A profile added User """
user = models.OneToOneField(User, on_delete=models.CASCADE)
# so to link the profile to a user
status = models.CharField(max_length=100, blank=True)
# a field status
def __str__(self):
return self.status
在admin.py中-我們正在將新創建的配置文件集成到用戶
class ProfileInline(admin.StackedInline):
model = Profile
can_delete = False
verbose_name_plural = 'Profile'
fk_name = 'user'
class CustomUserAdmin(UserAdmin):
inlines = (ProfileInline, )
def get_inline_instances(self, request, obj=None):
if not obj:
return list()
return super(CustomUserAdmin, self).get_inline_instances(request, obj)
# And then we unregister the User class and register the two updated ones
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
不要忘記運行/manage.py makemigrations
,然后執行/manage.py migrate
以更新數據庫。
讓我知道是否能回答您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.