Reputation: 703
I have a customer table which has 3 columns customer_id, first_name, last_name and the customer_id is the primary key.
See my views.py:
def addressHome(request):
customerList = Customer.objects.raw('select * from customers')
print(customerList.columns)
return render(request, "Address.html", {'customerList': customerList})
my models.py like this:
# -*- 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)
And my Address.html is like this:
{% 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 %}
below is the effect on the web page:
So, can someone tell me why and how to fix this problem?
Upvotes: 0
Views: 39
Reputation: 1131
You have defined your primary key as customerId
,
but you are calling the field in template as {{ row.customer_id }}
The db_column
option only changes the column name in database, but you should always call it with the name defined in Model
see here. This applies to all the field you have defined in template.
You should try this with {{ row.customerId }}
.
Also the view can be transformed into
def addressHome(request):
customerList = Customer.objects.all()
return render(request, "Address.html", {'customerList': customerList})
And in template
<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>
Upvotes: 1