简体   繁体   中英

Cannot display foreign key in Django list view

I'm trying to display the foreign key information in my list view for the primary key and it's just not displaying and I cannot for the life of me figure out why.

Models:

Primary

class LightHouse(models.Model):
    customer = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE,  related_name='lighthouse_group')
    context_object_name = 'lighthouse'
    lighthouseName = models.CharField(max_length=35, default="Not a lighthouse")

Foreign

class Endpoint(models.Model):

    lighthouse = models.ForeignKey(LightHouse, on_delete=models.CASCADE, related_name='LHName')
    device = models.CharField(max_length=50, unique=True)

Django Template for the PK

<tbody>
          {% for endpoint in lighthouse.endpoint_set.all%}
          <ul>
            <td>{{ endpoint.device }}</td>
            <td>{{ endpoint.endpointIPv4 }}</td>
            <td> Online </td>
          </ul>
          {% endfor %}
        </tbody>

What am I missing that it won't display the FK?

For your question "I cannot for the life of me figure out why." the reason is when you try to view a foreign key data you must view it as list of objects for your situation "lighthouse" is a foreign key for "LightHouse" Model so when try to view "lighthouseName" you should display it on this way "{{lighthouse.lighthouseName}}" for single row of data.

      {% for endpoint in lighthouse.endpoint_set.all%}
      <ul>
        <td>{{ endpoint.device }}</td>
        <td>{{ endpoint.lighthouse.lighthouseName}}</td>
        <td> Online </td>
      </ul>
      {% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM