主键无法显示在网页上

时间:2018-06-25 02:06:12

标签: django

我有一个customer表,其中有3列customer_id,first_name,last_name,并且customer_id是主键。

查看我的views.py:

def addressHome(request):
    customerList = Customer.objects.raw('select * from customers')
    print(customerList.columns)
    return render(request, "Address.html", {'customerList': customerList})

我的models.py像这样:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models

class Customer(models.Model):
     customerId = models.IntegerField(db_column='customer_id', primary_key=True, editable=False)
     firstName = models.CharField(max_length=30)
     lastName = models.CharField(max_length=30)

我的Address.html是这样的:

{% extends 'base.html' %}

{% block title %} Address List Page {% endblock %}

{% block content %}
<style>
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
</style>
<table width="50%" aligh="center">
    <tr>
                <th>Cutomer ID </th>
        <th>First Name</th>
        <th>Last Name</th>
    </tr>
    {% for row in customerList %}
        <tr>
            <td>{{ row.customer_id }} </td>
            <td>{{ row.first_name }} </td>
            <td>{{ row.last_name }}</td>
        </tr>
    {% endfor %}
</table>
{% endblock %}

以下是网页上的效果:
enter image description here

那么,有人可以告诉我为什么以及如何解决此问题吗?

1 个答案:

答案 0 :(得分:1)

您已将主键定义为customerId

但是您将模板中的字段称为{{ row.customer_id }} db_column选项仅更改数据库中的列名称,但是您应始终使用Model中定义的名称来调用它,请参见here。这适用于您在模板中定义的所有字段。

您应该尝试使用{{ row.customerId }}

也可以将视图转换为

def addressHome(request):
    customerList = Customer.objects.all()
    return render(request, "Address.html", {'customerList': customerList})

在模板中

<table width="50%" aligh="center">
    <tr>
        <th>Cutomer ID </th>
        <th>First Name</th>
        <th>Last Name</th>
    </tr>
    {% for row in customerList %}
        <tr>
            <td>{{ row.customerId }} </td>
            <td>{{ row.firstName }} </td>
            <td>{{ row.lastName }}</td>
        </tr>
    {% endfor %}
</table>