Skip to content
Advertisement

How to call OneToOneField reverse relationship in template (django)?

I have these models in my models.py
User Model

JavaScript

UserInfo Model

JavaScript

My-template
In my template i am passing some filtered User Profiles(let’s say filtering by age, if age > 25 ) now i need to show the name of the user(first_name) as well but i don’t know how to call a OneToOnefield reversely. Help is really appreciated :).

JavaScript

EDIT : My views.py:
I am passing a list named profiles which have filtered profiles based on 2-3 different type of filters so the code will be too much to paste here with all the references, I am pasting short version here:

JavaScript

Pasting the output here

JavaScript

Thanks :)

Advertisement

Answer

As @khadim hussen wrote in the comment you should use the following syntax:

JavaScript

Where p is your UserInfo model and p.user is the reference to the OneToOne realationship.

Note that when you don’t have a related user with p -> user the value you will return is None.

If you want to show different info than None in your template just can do the following validation:

JavaScript

But in your views yo will get a RelatedObjectDoesNotExists to ensure in your views that the relationship exists you can make the following validation:

JavaScript

Other thing that is important is when you have a related_name property as in your example:

JavaScript

So in this case you need to refer to the user property with the related_name.

In a more concrete way you have to do as following:

JavaScript

One important thing is that if you ar using queryset.filter(...).values() so if you want to load values from other model you can use the following:

JavaScript

That’s it.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement