【问题标题】:Django - how to query user profile based on User model having OneToOneFieldDjango - 如何根据具有 OneToOneField 的用户模型查询用户配置文件
【发布时间】:2017-03-22 16:29:20
【问题描述】:

我正在使用 Django,并且是编程新手。我想知道如何查询与用户模型具有 OneToOne 关系的用户的个人资料。这是我的代码:

models.py:

class User(models.Model):

    email = models.EmailField(unique=True, null=True)
    date_joined = models.DateTimeField(default=datetime.now)
    username = models.CharField(max_length=22)

class UserProfile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    company_name = models.CharField(max_length=500)
    contact_person = models.CharField(max_length=255)
    country = models.CharField(max_length=100)
    city = models.CharField(max_length=100)

如果用户注册并在验证后填写他的个人资料。我如何通过views.py查询数据库,对于任何特定用户,他的UserProfile信息是什么。例如,使用电子邮件 example@examplemail.com 的用户的公司名称或国家/地区是什么

顺便说一句,这也是我在 Django 中捕获有关用户的其他信息的最佳实践吗?

【问题讨论】:

    标签: python django


    【解决方案1】:

    您可以像这样获取用户并使用其 UserProfile:

    # Make sure you create a UserProfile when you create a new User
    user = User.objects.get(email='example@examplemail.com')
    user.userprofile.company_name
    user.userprofile.country
    

    是的,这是向默认 django 用户模型添加额外字段的推荐方法。请参阅this 问题。如果您使用自己的 User 模型,您只需将 UserProfile 字段添加到 User 模型。

    【讨论】:

      猜你喜欢
      • 2017-07-14
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 2014-06-17
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      相关资源
      最近更新 更多