简体   繁体   English

Model.objects.get()有效,但在使用ForeignKey属性时无效

[英]Model.objects.get() works, but not when using a ForeignKey attribute

I have a profile model that looks like this: 我有一个如下的个人资料模型:

class Profile(models.Model):
    username = models.ForeignKey(User, blank=True, null=True)
    age = models.IntegerField(default=0)
    points = models.IntegerField(default=100)

    def __str__(self):
        return str(self.username)

Here's my template 这是我的模板

<h3><a href="{% url 'profile' u=i.user %}" class='username_foreign'>{{ i.user }}</a></h3>

which points to this url: 指向此网址:

url(r'^profile/(?P<u>\w+)/', profile, name='profile')

and here's my view function: 这是我的视图函数:

def profile(request, u):
    if request.method == 'GET':
        profile = Profile.objects.get(username=u)

    return render(request, 'base.html', {})

As you can see here I pass through u which is the username. 如您所见,我通过了用户名u But when I try to get() the profile via the username passed through, I get this error: 但是,当我尝试通过传递的username get() profile ,出现此错误:

ValueError at /profile/zorgan/

invalid literal for int() with base 10: 'zorgan'

However when I use get() on any other attribute of my Profile model, it works fine. 但是,当我在Profile模型的任何其他属性上使用get()时,它可以正常工作。 And it even prints my username . 它甚至会打印我的username So when I do this: 所以当我这样做时:

def profile(request, u):
    if request.method == 'GET':
        print(u) #prints username
        profile = Profile.objects.get(points=50)
        print(profile.username) #successfully prints username (same as 'u')

    return render(request, 'base.html', {})

As you can see above, getting the Profile object via its attribute doesn't work for username . 如您在上面看到的,通过username属性获取Profile对象不适用于username And the problem isn't related to the u as that successfully prints aswell. 问题与u无关,因为u也可以成功打印。 Any idea what the problem is? 知道是什么问题吗?

The field you've called username isn't a username at all. 您称为username的字段根本不是用户名。 It's a ForeignKey, which is an integer value pointing at a row in another table. 这是一个ForeignKey,它是指向另一个表中一行的整数值。 You should call it what it is: user . 您应该将其命名为: user

To look up the actual username, in the User table, you need to use the double-underscore syntax. 要在User表中查找实际的用户名,您需要使用双下划线语法。 This would work: 这将工作:

profile = Profile.objects.get(username__username=u)

but as I said, you should really rename that username field, in which case you would do: 但是正如我所说,您应该真正重命名该username段,在这种情况下,您应该这样做:

profile = Profile.objects.get(user__username=u)

Another way to do it would be to look up the User directly and then get the Profile: 另一种方法是直接查找用户,然后获取配置文件:

user = User.objects.get(username=u)
profile = user.profile

but this takes two separate queries, rather than one joined one. 但这需要两个单独的查询,而不是一个合并的查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM