Django访问OneToOneField [英] Django accessing OneToOneField

查看:60
本文介绍了Django访问OneToOneField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建扩展用户的视图:

class Client(models.Model):
    user = models.OneToOneField(User, related_name='user')

    def __unicode__(self):
          return "%s" % (self.user)   

我当前正在尝试通过访问客户端对象来访问用户模型.目前,我在python shell中遇到错误:

I am currently trying to access the User model by accessing the Client object. At the moment I am getting an error in the python shell:

ValueError: invalid literal for int() with base 10:

我知道它与访问OneToOneField有关,但我不知道为什么.在我看来,我发现的所有解决方案都是从用户模型的角度来看的,而不是扩展的客户端.

I know it has something to do with accessing an OneToOneField but I don't know why. All the solutions I found were from the perspective of the User model and not the extended Client, in my case.

使其更加清晰.每当我访问用户时.

To make it abit clearer. Whenever I access the User.

>>> client1 = User.objects.get(username="client1")
>>> client1.user
>>> client1.user.attribute

它回显扩展模型的属性,在本例中为Client属性.我如何才能做到这一点.因此,通过客户端模型而不是用户模型.

It echos the attributes of the extended Model, in this case the Client attribute. How can I achieve this the other way around. So through the Client model instead of the User model.

推荐答案

我认为您需要传递用户对象而不是字符串.

I think you need to pass the user object and not a string.

client1 = User.objects.get(username="client_1") # this is the user object
client_obj = Client.objects.get(user=client1) # pass object NOT STRING

您还可以执行以下操作:(假设提供了用户ID)

you can also do this: (assuming the user's id is given)

client1 = Client_objects.get(user__id=1) # pass the user's id instead

我希望它能起作用;)

这篇关于Django访问OneToOneField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆