0

I am getting postgresql data from my server and fill out the table down below. I was able to join 3 different tables and get columns I want from them.

However, it gives me none-formatted object. Is there any way I can fill out the table using joined query one by one..?

enter image description here

enter image description here

views.py

 vlan_query_results = Vlans.objects.select_related('vlan_id').values_list('name', 'gateways__vip', 'gateways__backup', 'gateways__master', 'gateways__nat', 'gateways__vhid', 'subnets__dhcp', 'subnets__dns').order_by('vlan_id')

template

 {% for object in vlan_query_results %}
    <tr  #id='items-table'>
      <th scope="row" class="checkbox-row"><input type="checkbox" name="item" /></th>
        <th scope="row">{{ forloop.counter }}</th>


     <td class="item"> {{object }}</td>
 <td class="item"> </td>

    </tr>
{% endfor %}
Angie
  • 9
  • 7

1 Answers1

0

Maybe instead using values_list, you should use DRF Serializers to get the response in a dictionary like structure with only the fields you want.

from rest_framework import serializers

class VlansSerializer(serializers.ModelSerializer):
    gateways_vip = serializers.ReadOnlyField(source='gateways__vip')
    gateways_backup = serializers.ReadOnlyField(source='gateways__backup')
    gateways_master = serializers.ReadOnlyField(source='gateways__master')
    gateways_nat = serializers.ReadOnlyField(source='gateways__nat')
    gateways_vhid = serializers.ReadOnlyField(source='gateways__vhid')
    subnets_dhcp = serializers.ReadOnlyField(source='subnets__dhcp')
    subnets_dns = serializers.ReadOnlyField(source='subnets__dns')

    class Meta:
    model = Vlans
    fields = ('name', 'gateways_vip', 'gateways_backup', 'gateways_master', 'gateways_nat', 'gateways_vhid', 'subnets_dhcp', 'subnets_dns')

In your views.py: vlan_query_results = VlansSerializer(Vlans.objects.all(), many=True).data

In your html:

{% for object in vlan_query_results %}
<tr>
  <th scope="row" class="checkbox-row">
     <input type="checkbox" name="item" />
  </th>
  <th scope="row">{{ forloop.counter }}</th>
  <td class="item">{{object.name}}</td>
  <td class="item">{{object.gateways_vip}}</td>
</tr>
{% endfor %}

You have to add the rest of the <td></td> tags in a similar manner. Also, you cant add the #id='items-table' to the <tr> since it is in a loop and ids are supposed to be unique in a html page.

Hope this helps. :)

Ruhi123
  • 99
  • 6