【问题标题】:What is the best way to query for instances of django models with one to one relationships with users查询与用户具有一对一关系的 django 模型实例的最佳方法是什么
【发布时间】:2012-09-23 22:46:30
【问题描述】:

假设您有一个 django 模型,该模型与用户具有 OneToOne / Unique ForeignKey 关系,如Django documentation on how to create a UserProfile. 所示:

现在假设您有一个视图方法,该方法接受您可以从中获取用户的请求。查询与该用户关联的个人资料的最佳方式是什么?

from django.contrib.auth.models import User

# sample user profile model associated with user
class UserProfile(models.Model):
    likes_spam = models.BooleanField()
    user = models.OneToOneField(User)

#view method
def forward_to_practice_home(request):
    user = request.user
    profile_for_user = #insert code here that would get the profile for that user

【问题讨论】:

    标签: python django


    【解决方案1】:
    【解决方案2】:

    related_names 非常有帮助。如果您将用户配置文件定义更改为:

    class UserProfile(models.Model):
        likes_spam = models.BooleanField()
        user = models.OneToOneField(User, related_name='profile')
    

    那么您可以按如下方式使用配置文件:

    def forward_to_practice_home(request):
        user = request.user
        profile_for_user = user.profile
    

    【讨论】:

      【解决方案3】:

      你可以使用一种叫做get_profile()的特殊方法

      profile_for_user = user.get_profile()
      

      请注意,您必须在 settings.py 中设置AUTH_PROFILE_MODULE

      但是,这在 Django 1.5 中已被弃用,因为它添加了对 user model customization 的支持

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-21
        • 2011-12-06
        • 1970-01-01
        • 2020-02-03
        • 2021-10-26
        • 1970-01-01
        相关资源
        最近更新 更多