EN VI

Django Related Object Reference in Template?

2024-03-14 05:30:06
How to Django Related Object Reference in Template

Unable to display related object reference set via foreign key relationship in HTML template.

Here's the code so far.

models.py:

class MprVw(models.Model):
    payloadid = models.TextField(db_column='payLoadID', blank=True, null=True)
    file = models.TextField(db_column='File', primary_key=True)
    class Meta:
        managed = False
        db_table = 'MPR_VW'


class MprWi(models.Model):
    id = models.TextField(db_column='id', primary_key=True)
    payloadid = models.TextField(db_column='payLoadID', blank=True, null=True)
    file = models.ForeignKey(MprVw, on_delete=models.DO_NOTHING, db_column='File')
    class Meta:
        managed = False
        db_table = 'MPR_WI'

views.py:

def MPR(request):
  
  myDls = request.GET.get("dls")
  myMPR = MprVw.objects.filter(dls=myDls)
  myMprWi = MprWi.objects.select_related("file")
  context = {
    'myMPR': myMPR,
    'myMprWi': myMprWi,
    'myDls': myDls,
  }
  MPR = loader.get_template('MPR.html')
  return HttpResponse(MPR.render(context, request))

HTML:

                {% for rowmyMPR in myMPR.mprwi_set.all %}
                <tr>
                    <td>{{ rowmyMPR.file }} 
                        {{ rowmyMPR.id }} 
                    </td>
                </tr>
                {% endfor %}

I am expecting to display row data from myMprWi that are the child records of the myMPR parent file. There is data displayed with "MprVw object ()" around it. How do I get ride of that?

For example: MprVw object (< the row file number>) <the row id number>

Solution:

myMPR is not a MprVw object, but a QuerySet of zero, one, or multiple MprVw items. You thus will need to enumerate to get such object, so:

from django.shortcuts import render


def MPR(request):
    myDls = request.GET.get('dls')
    myMPRs = MprVw.objects.filter(dls=myDls)
    context = {
        'myMPRs': myMPRs,
        'myDls': myDls,
    }
    return render(request, 'MPR.html', context)

and in the template:

{% for myMPR in myMPRs %}
  {% for rowmyMPR in myMPR.mprwi_set.all %}
    <tr>
        <td>{{ rowmyMPR.file }} 
            {{ rowmyMPR.id }} 
        </td>
    </tr>
  {% endfor %}
{% endfor %}
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login