Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 578
Kipt Scriddy Avatar asked Oct 01 '22 06:10

Kipt Scriddy


1 Answers

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 ;)

like image 190
Earvin Gemenez Avatar answered Oct 05 '22 13:10

Earvin Gemenez