【问题标题】:How to access OneToOneField in the shell如何在 shell 中访问 OneToOneField
【发布时间】:2016-06-04 04:28:07
【问题描述】:

问题

我正在尝试从通过OneToOneField 链接到MyUserclass UserProfile 中获取变量website

为此,我尝试了python manage.py shell

from models import *

myuser = MyUser.objects.get(email="dummy@domain.tld")
myuser_profile = UserProfile(user=myuser)

myuser_profile.website

但这会返回给我u'',而不是我可以在admin 网站上看到的网站地址。这不是访问变量的正确方法还是需要我在其他地方查找失败?

配置

models.py

class MyUserManager(BaseUserManager):
    def create_user(self, email, password=None):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(email, password=password)
        user.is_admin = True
        user.save(using=self._db)
        return user

class MyUser(AbstractBaseUser):
    email = models.EmailField(verbose_name='email address', max_length=255, unique=True,)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):            # __unicode__ on Python 2
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

    def __unicode__(self):
        return self.email


class UserProfile(models.Model):
    # This line is required. Links UserProfile to a User model instance.
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                related_name='MyUser'
                                )

    # The additional attributes we wish to include.
    website = models.URLField(blank=True)


    # Override the __unicode__() method to return out something meaningful!
    def __unicode__(self):
        return self.user.email

admin.py

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    max_num = 1
    can_delete = False

class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'is_admin')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Permissions', {'fields': ('is_admin',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'password1', 'password2')
        }),
    )
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()

    inlines = [UserProfileInline]


    # Now register the new UserAdmin...
    admin.site.register(MyUser, UserAdmin)

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    您正在创建UserProfile 的新实例,而不是从数据库中加载现有实例。

    您可以使用

    访问OneToOne关系
    myuser = MyUser.objects.get(email="dummy@domain.tld")
    profile = myuser.userprofile   # access the onetoone relation
    profile.website   
    

    您可以在django docs 中了解有关OneToOne 关系的更多信息

    【讨论】:

    • 如果我尝试这样做,我在执行profile = myuser.userprofile:AttributeError: 'MyUser' object has no attribute 'userprofile'时会在第二步出错
    • 嗯。尝试从 OneToOne 字段中删除“related_name”属性?
    • 现在它可以工作了 - 你知道为什么没有related_name 属性它可以工作吗?我添加了这个是因为一个关于如何reverse access onetoone fields 的答案
    • related_name 引用了您如何从相关对象(在您的情况下)MyUser 访问UserProfile。所以你可以访问与myuser.myuser 的关系,这是没有意义的。您应该跳过related_name 或选择更好的名称,例如userprofile
    猜你喜欢
    • 2014-04-30
    • 2011-10-04
    • 2016-01-17
    • 2013-03-09
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    相关资源
    最近更新 更多