python - 如何通过 Django 中的外键访问过滤器参数中的数据?

标签 python django django-models foreign-keys django-views

我有两个模型: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/

相关文章:

django - 如何按外部值对Django QuerySet进行排序?

Pythonpipbuilder : resolve dependencies - list index out of range

python - 是否可以在Hive中按列表查询?

django - Celery 延迟回调

python - ManytoMany 与 django Rest 相关

django - 如何在 django 中从 QueryDict 创建对象?

python - 对没有迁移的应用程序的依赖 : %s"% key[0]) in the Django

django - BooleanField 中的 'default=True' 有什么意义

python - Pandas 按时间分组,指定开始时间非整数分钟

python - 如何使用 Google Vision API 从 base64 编码图像中进行文本检测?