我有两个模型:用户(由Django预定义)和通过外键连接的UserProfile .
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name="connect")
location = models.CharField(max_length=20, choices=LOCATION_CHOICES)
gender = models.CharField(max_length=20, choices=GENDER_CHOICES)
User模型包含username,first_name,last_name和password等字段 .
在我看来,我想使用位于用户对象中的用户名字段找到UserProfile对象 . 要使用用户名字段过滤/获取UserProfile对象,我需要通过外键“旅行”以访问用户模型 .
但是,我在尝试这样做时遇到了一些错误 . 有谁知道我怎么做到这一点?
这是我到目前为止:
def edit(request):
#the line below is where I am facing troubles.
#The error I'm getting is SyntaxError: keyword can't be an expression
user = UserProfile.objects.filter(user.username=request.user.username)
form1 = UserEditForm()
form2 = UserProfileEditForm()
c = RequestContext(request, {
'action': 'update/',
'button': 'Update',
'form1': form1,
'form2': form2,
})
return render_to_response('registration/user_profile.html', c)
有谁知道如何解决这个问题?谢谢!
1 回答
使用双下划线(
__
)来遍历关系 . 例如 . :但是,在您的情况下,您不需要这样做 .
request.user
是User
对象,所以要让他们的UserProfile
只做:甚至:
请注意,您的第一个示例应返回
QuerySet
,结果为1,而第二个示例返回单个对象 . 换一种说法: