没有这样的列:student_student.course_id

no such column: student_student.course_id

我正在使用 Django Sqlite 创建一个简单的系统,但每当我尝试通过单击学生 table 在 django/admin 中以管理员身份打开 table 时,我都会遇到此错误。错误如下:

OperationalError at /admin/student/student/

no such column: student_student.course_id

我搜索了 allot,但没有找到解决我的问题的任何确切方法。

以下是我的代码。

views.py

from django.shortcuts import render

from .models import Student
# Create your views here.

def index(request):
    return render(request, "student/index.html",{
        "student": Student.objects.all()
    })

index.html

    {% extends "student/layou.html" %}

{% block body %}
    <h2>Student information</h2>
    <ul>
        {% for student in Student %}
            <li>  {{ student.id }} Student Full Name: {{ student.f_name }}{{ student.l_name }} in {{ student.grade }} with {{ student.gpa }}  in {{ student.course_id }}</li>
            {% empty %}
                No information entered
        {% endfor %}
    </ul>
{% endblock %}

models.py

from django.db import models

# Create your models here.


class Course(models.Model):
    code = models.CharField(max_length=10)
    course_name = models.CharField(max_length=64)

    def __str__(self):
        return f"Course name: {self.course_name} with course code ({self.code})"

class Student(models.Model):
    f_name = models.CharField(max_length=64)
    l_name = models.CharField(max_length=64)
    course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name= "Classes" )
    grade = models.CharField(max_length=10)
    gpa = models.DecimalField(max_digits=4.0, max_length=4, decimal_places=2)

    def __str__(self):
        return f"{self.id} Full Name:  {self.f_name} {self.l_name} in {self.grade} with a gpa {self.gpa} in course {self.course_id}"

您不能通过 Student 对象引用 Course 对象:

{{ student.course_id }}

你可以像这样获取对象或它的 id:

{{ student.course }}      # returns related Course object
{{ student.course.id }}   # returns related Course object's id

为了将来参考,您还想做更多的改变:

"student": Student.objects.all()
# change to:
"students": Student.objects.all()

{% for student in Student %}
# change to:
{% for student in students %}

{% extends "student/layou.html" %}
# probably change to:
{% extends "student/layout.html" %}