简体   繁体   English

在Django上向模型添加字段的正确方法

[英]Correct way to add fields to a model on django

I have a User model and i want to add a new field to the user, in the database and in the user form. 我有一个用户模型,我想在数据库和用户表单中向用户添加一个新字段。 i have looked online many differente ways to do this but i want to know what is the "correct" way to do it. 我已经在网上查看了许多不同的方法来执行此操作,但是我想知道什么是“正确”的方法。 Specially the correct way to create migrations. 特别是创建迁移的正确方法。

Django Version: (1,10,0,u'final',1) Django版本:(1,10,0,u'final',1)

Not sure if I got what you're looking for but let's say you want to add a "Status" field to your User model, and then have it in the Admin panel so you can interact with it (update, change, etc...). 不确定我是否找到了您想要的东西,但是假设您要向“用户”模型中添加“状态”字段,然后将其放入“管理”面板中,以便可以与它进行交互(更新,更改等)。 )。

in models.py - we are creating a Profile class which will be linked to a User and then a status to be added to a user: 在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

in admin.py - we are integrating the newly created Profile to the user 在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)

Don't forget to run /manage.py makemigrations and then /manage.py migrate to update the database. 不要忘记运行/manage.py makemigrations ,然后执行/manage.py migrate以更新数据库。

Let me know if that answer your question. 让我知道是否能回答您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM