简体   繁体   中英

Extending User Model in Django Issues

I'm currently running Django 1.6 and trying to extend the users model using this tutorial: https://docs.djangoproject.com/en/1.6/ref/models/fields/#django.db.models.OneToOneField The only way I can get it to work is if I create an AdditionalUser object and go backwards to reach the User model.

I used this code:

from django.db import models 
from django.contrib.auth.models import User

class AdditionalUser(models.Model):
    user = models.OneToOneField(User)
    hobby = models.CharField(max_length=50)
    weight = models.FloatField()

but when I try to do the following, it gives me False:

user = User.objects.get(pk=1)
hasattr(user, 'hobby')
False

I already ran syncdb after I created this new model. Is there anything I'm doing wrong?

The User object does not have the attributes you specify in AdditionalUser . However, it does have a additionaluser attribute:

user = User.objects.get(pk=1)
# create the AdditionalUser object
additional = AdditionalUser.objects.create(user=user)
hasattr(user.additionaluser, 'hobby')
True

The documentation on OneToOneField says this :

A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True, but the “reverse” side of the relation will directly return a single object. (...) If you do not specify the the related_name argument for the OneToOneField, Django will use the lower-case name of the current model as default value.

If the 'hobby' property does not exist in the User object, then you will always get False.

Try this:

user = AdditionalUser.objects.filter(user__id=1)[0]
hasattr(user, 'hobby')

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