假设您有一个django模型,它与一个用户具有OneToOne/Unique ForeignKey关系,如Django documentation on how to create a UserProfile.上所示:
现在假设您有一个view方法,它接受一个可以从中获取用户的请求。查询与该用户关联的概要文件的最佳方式是什么?你知道吗
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
您可以使用一个名为get_profile()的特殊方法
需要提醒的是,您必须在设置.py你知道吗
但是,django1.5中不赞成这种方法,因为它添加了对user model customization的支持
^{}
related_name
非常有用。如果将用户配置文件定义更改为:然后您可以使用以下配置文件:
相关问题 更多 >
编程相关推荐