我有两个模型:User(由 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)
用户模型包含用户名、名字、姓氏和密码等字段。
在我看来,我想使用位于用户对象中的用户名字段找到一个 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)
有人知道怎么解决吗?谢谢!
最佳答案
使用双下划线 (__
) 来遍历关系。例如:
user = UserProfile.objects.filter(user__username=request.user.username)
但是,对于您的情况,您不需要这样做。 request.user
是一个 User
对象,所以要获取他们的 UserProfile
只需执行以下操作:
user = request.user.get_profile()
甚至:
UserProfile.objects.get(user=request.user)
请注意,您的第一个示例应返回具有 1 个结果的 QuerySet
,而第二个示例返回单个对象。换句话说:
request.user.get_profile() ==
UserProfile.objects.filter(user__username=request.user.username)[0]
关于python - 如何通过 Django 中的外键访问过滤器参数中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11945206/