I've been working with an existing datatable, so I create the models using inspectdb. My class doesn't have a primary key, so Django adds an automatic primary key named id when I makemigrations and migrate. Later, when I define the template, views, and URLs to see the class table at my website, there is an error like this one:
no such column: AGC.id
I don´t know how to fix it, I'm new to using Django.
Model:
class Agc(models.Model):
index = models.BigIntegerField(blank=True, null=True)
area = models.TextField(db_column='AREA', blank=True, null=True) # Field name made lowercase.
periodo = models.BigIntegerField(db_column='PERIODO', blank=True, null=True) # Field name made lowercase.
demanda = models.TextField(db_column='DEMANDA', blank=True, null=True) # Field name made lowercase. This field type is a guess.
class Meta:
db_table = 'AGC'
Template:
{% extends "despachowebapp/Base.html" %}
{% load static %}
{% block content %}
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Index</th>
<th scope="col">Area</th>
<th scope="col">Periodo</th>
<th scope="col">Demanda</th>
</tr>
</thead>
<tbody>
{% if AGCs %}
{% for AGC in AGCs %}
<tr>
<th scope='row'>{{ Agc.id }}</th>
<td>{{ Agc.index }}</td>
<td>{{ Agc.index }}</td>
<td>{{ Agc.area }}</td>
<td>{{ Agc.periodo }}</td>
<td>{{ Agc.demanda }}</td>
</tr>
{% endfor %}
{% else %}
<h1>No hay datos </h1>
</tbody>
</table>
{% endblock %}
Views:
def index(request):
AGCs=Agc.objects.all()
contexto={'AGCs': AGCs }
return render(request,'OfertasAGC.html', contexto)
URLs:
urlpatterns =[
path('admin/', admin.site.urls),
path('', include('webapp.urls')),
path('prueba/',views.index),
]
Django models must always have a primary key, you can use AutoField or BigAutoField or use another model field, but you will need to add the primary_key = True attribute.
For example: