假设您有一个 django 模型,该模型与用户具有 OneToOne / Unique ForeignKey 关系,如Django 文档中有关如何创建 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