6

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.

Kipt Scriddy
  • 743
  • 2
  • 14
  • 22

1 Answers1

5

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

furins
  • 4,979
  • 1
  • 39
  • 57
Earvin Gemenez
  • 201
  • 1
  • 3
  • Thank you! As you can see I just edited my question before your answer. Seems the best work around! – Kipt Scriddy Mar 22 '14 at 15:59
  • 2
    Note that the same can be done in a single query: `Client.objects.get(user__username="client_1")`. Use `.select_related('user')` if you know you want to access the `User` object's data as well. – knbk Mar 22 '14 at 17:16