How to Call A Particular Relational Field in Django 3.*

I have two models like so:

class model1(model.Models):
   a=model.ForeignKey('model2', related_name ='c_caller') 
   x=model.ForeignKey(''model3")
   z= some_other_code

class Model2(model.Models):
   b=some codes
   c= some codes

class Model3(model.Models):
   y=some codes

in the views.py:

from .models import *
def a_show(requests):
   a_model=Model1.objects.all()
   html='h.html'    
   context = {'a_model':a_model}
   return render(request, html, context)

In the template file:
I must use a single for loop to call each fields

{%for a in a_model %}
  {{a.c_caller.c}}
  {{a.x}}
  {{a.z}}
{%endfor%}

What I am trying to do is that anytime I call a in the html, then {{a_model.c_caller.c}} should render value of c that is in Model2

Unfortunately the above implementation isn’t working to call c, please how can I do this?

The related name (c_caller in this case) is only used for the reverse relationship. You should only need a.c for this.

1 Like