Home > Blockchain >  For loop in template django with prefetch_related
For loop in template django with prefetch_related

Time:03-14

I got an issue when trying to access values from other models by using prefetch_related

My model:

class testimport(models.Model):
    id=models.AutoField(primary_key=True)
    so_hd=models.CharField( max_length=50, unique=True)
    ten_kh=models.CharField( max_length=500)
    tien_dong=models.IntegerField(blank=True, null=True)
    created_at=models.DateTimeField(auto_now_add=True)
    objects=models.Manager()
    def get_absolute_url(self):
        return "/chi_tiet_hop_dong/%s/" % self.so_hd
class report(models.Model):
    id=models.AutoField(primary_key=True)
    so_hd=models.ForeignKey(testimport, on_delete=models.DO_NOTHING, to_field="so_hd")
    nhan_vien=models.ForeignKey(Callers, on_delete=models.DO_NOTHING, null=True, blank= True, to_field="admin_id")
    noi_dung=models.TextField()

My views: ....

get_contract_detail=testimport.objects.filter(so_hd__in=get_user).order_by("id").prefetch_related().values()
contract=get_contract_detail.filter(so_hd=so_hd).all()
return render(request, "caller_template/contract_detail.html", {"contract":contract,"the_next":the_next,"the_prev":the_prev, "so_hd":so_hd,"form":form,"form1":form1})

If I try to print out the content by values, it is ok:

print(get_contract_detail.filter(so_hd=so_hd).values("so_hd","report__noi_dung"))

In my template:

{% for report in contract %}
   {%  for content in report.so_hd.all%}
        <tr>
             <td>{{ forloop.counter }}</td>
             <td>{{content.noi_dung}}</td>
        </tr>
    {% endfor %}
 {% endfor %}

There is no content in cells. How can I show the content Please help

CodePudding user response:

The reason this does not work is because of the use of .values(…) [Django-doc]. Furthermore you did not specify a related_name=… parameter [Django-doc], so that means that you access the reports with .report_set.all():

contract = testimport.objects.filter(
    so_hd__in=get_user, so_hd=so_hd
).order_by('id').prefetch_related()  # no .values()
context = {
    'contract': contract,
    'the_next': the_next,
    'the_prev': the_prev,
    'so_hd': so_hd,
    'form': form,
    'form1':form1
}
return render(request, 'caller_template/contract_detail.html', context)

and in the template render with .report_set.all:

{% for report in contract %}
   {% for content in report.report_set.all %}
        <tr>
             <td>{{ forloop.counter }}</td>
             <td>{{ content.noi_dung }}</td>
        </tr>
    {% endfor %}
 {% endfor %}
  • Related