【问题标题】:Django 1-1 relationship how toDjango 1-1 关系如何
【发布时间】:2011-02-22 16:44:00
【问题描述】:
profile = UserProfile.objects.get(....)

我尝试做的是获取当前登录用户的个人资料。括号里应该填什么?

【问题讨论】:

    标签: django django-models django-users


    【解决方案1】:

    假设您遵循此处描述的模式:

    http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

    您应该能够使用以下内容:

    def my_view(request):
        user = request.user
        if not isinstance(user, AnonymousUser):
            profile = user.get_profile()
            # do something with the profile here
        else:
            # handle anonymous users
    

    【讨论】:

      【解决方案2】:

      普通人,没必要这么苛刻...有些人实际上不知道灰色轮廓复选标记是您应该按下的。

      UserProfile.objects.get(user=request.user) 
      

      但如果是OneToOne 字段,你应该可以做到request.user.userprofile http://docs.djangoproject.com/en/dev/topics/db/queries/#one-to-one-relationships

      【讨论】:

      • 谢谢Yuji,原来如此。对不起,我还是个初学者^^
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 2014-04-19
      相关资源
      最近更新 更多