简体   繁体   中英

Django accessing OneToOneField

Made a view that extended User:

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

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

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:

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

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

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

I hope it works ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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