主键无法在网页上显示

问题描述 投票:0回答:1

我有一个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

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

django
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.