如何与django联系表?

时间:2017-10-13 03:53:49

标签: python django django-models django-templates django-views

假设,我有两张桌子: enter image description here

我做了models.py:

class Score(models.Model):
    Student_Id = models.CharField(max_length=20, primary_key=True)
    Grade = models.CharField(max_length=30)
    Status= models.CharField(max_length=3)

    class Meta:
        db_table ='T_Score'


class Student(models.Model):
    Student_Id = models.CharField(max_length=20, primary_key=True)
    Student_Name = models.CharField(max_length=30)
    Student_Class = models.CharField(max_length=3)

    def __str__(self):
        return {
            "id" : self.Student_Id,
            "name" : self.Student_Name,
        }

    class Meta:
        db_table ='T_Student'

如果Student.Student_Id只是作为主键(不是外国的),是否可以加入表格?我应该如何制作代表学生ID,学生姓名和成绩的view.py和模板? 提前谢谢。

2 个答案:

答案 0 :(得分:0)

我并不是真的使用Django,但就加入这两个表而言,你可以。连接具有主键和外键关系的两个表实际上与在行上放置普通RESTRICT操作相同,即通过显式使用。在哪里Students.students_id = Score.students_id。普通加入会自动为您计算。

答案 1 :(得分:0)

I would suggest you update your models.py.

class Student(models.Model):
    name = models.CharField(max_length=30)
    s_class = models.CharField(max_length=3)

class Score(models.Model):
    student = models.ForeignKey(Student)
    grade = models.CharField(max_length=30)
    status= models.CharField(max_length=3)

You can access the Score model in the views.py

scores = Score.objects.all()
context = {
    'scores': scores
}

Accessing scores in the HTML template

{% for score in scores %}
    ID - {{ score.student.id }}
    NAME - {{ score.student.name }}
    GRADE - {{ score.grade }}
{% endfor %}
相关问题