简体   繁体   中英

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)

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:

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

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.

Let me know if that answer your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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