Extending User object in Django: User model inheritance or use UserProfile?

前端 未结 2 1661
旧时难觅i
旧时难觅i 2021-02-05 11:36

To extend the User object with custom fields, the Django docs recommend using UserProfiles. However, according to this answer to a question about this from a year or so back:

2条回答
  •  梦毁少年i
    2021-02-05 11:48

    I vote for using UserProfiles.

    I use several thrid party apps. And a foreign key to a User will always Point to auth.models.User.

    Example:

    class Article(models.Model):
        user = models.ForeignKey('auth.User') # instead of your CustomUser
        text = ....
    

    And your custom User model:

    class CustomUser(User):
        timezone = models.CharField(max_length=50, default='Europe/London')
    
        # Use UserManager to get the create_user method, etc.
        objects = UserManager()
    

    What will be happen if you access the user field through an Article instance? This will raise an exception:

    u = a_article.user
    u.timezone
    
    AttributeError: 'User' object has no attribute 'timezone'
    

    Maybe this isn't a problem for you and you wan't to avoid the additional DB query. But i would use the get_profile way.

    UPDATE May, 2013

    Since Django 1.5 you can extend the default User model, or substitute with a completely customized model.

    UPDATE Nov, 2016

    The above solution is obsolete, see the comment from wim

提交回复
热议问题