Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse relationship for OneToOneField Django?

Tags:

python

django

I am using User model

 from django.contrib.auth.models import User

UserProfile model extends User model

class UserProfile(models.Model):
    user   = models.OneToOneField(User, related_name='userprofiles')
    avatar = models.FileField('img',upload_to='./static/image/')

I need to take user's avatar, I am doing something like

user = User.objects.get(pk=1)

user.userprofiles

But it throws me error

RelatedObjectDoesNotExist: User has no userprofile.

Trace:

In [5]: user = User.objects.get(pk=1)

In [6]: user.userprofiles
---------------------------------------------------------------------------
RelatedObjectDoesNotExist                 Traceback (most recent call last)
<ipython-input-6-2253b19e792d> in <module>()
----> 1 user.userprofiles

C:\Program Files\Anaconda3\lib\site-packages\django\db\models\fields\related_des
criptors.py in __get__(self, instance, cls)
    405                 "%s has no %s." % (
    406                     instance.__class__.__name__,
--> 407                     self.related.get_accessor_name()
    408                 )
    409             )

RelatedObjectDoesNotExist: User has no userprofiles.
like image 269
vinoth kumar Avatar asked Oct 16 '25 10:10

vinoth kumar


1 Answers

You have a typo in the following:

 user   = models.OneToOneField(User, related_name='userprofiles')
 # userprofiles with 's'

Whereas, you have tried to have access to it with user.userprofile without s

Either you remove the s in the related_name='userprofiles', or add s: --> user.userprofiles to access the Userprofile.

like image 137
Lemayzeur Avatar answered Oct 19 '25 01:10

Lemayzeur