读取具有两个外键列的表数据

时间:2019-11-20 06:29:15

标签: python sqlalchemy flask-sqlalchemy

我有三个表,分别称为学生,部门,学生部门。 学生表模式为

student_id integer primary key ,student_name char 

部门表架构为

department_id integer primary key ,department_name char

学生部门表架构为

combo_id integer primary key,student_id integer,department_id integer,foreign key(student_id) references student,foreign key(department_id) references department

我正在使用的后端是sqlite。前端是Python,Flask和SQL炼金术。

我的问题是 我试图从学生部门表中读取一些值。 我使用的格式是

student_user = studentdepartment.query.all()

但是我得到的结果是'None'。

但是我必须读取表数据。 有人可以帮我如何从表格中读取数据吗?

我的models.py看起来像这样

from my_app import db
from sqlalchemy import Integer, ForeignKey, String, Column

class students(db.Model):
    "Adding the students" 
    students_id = db.Column(db.Integer,primary_key=True)   
    students_name = db.Column(db.String(50),nullable=False)
    students_email = db.Column(db.String(50),nullable=False)
    students_designation = db.Column(db.String(40),nullable=False)

    def __repr__(self):
        return f"students('{self.students_name}', '{self.students_email}','{self.students_designation}')"

class studentstimeslots(db.Model):
    "Adding the timing for students" 
    time_id = db.Column(db.Integer,primary_key=True)   
    students_id = db.Column(db.Integer,ForeignKey(studentss.students_id),nullable=False)    
    students_start_time = db.Column(db.String,nullable=False)
    students_end_time = db.Column(db.String,nullable=False)

    def __repr__(self):
        return f"studentstimeslots('{self.students_id}', '{self.students_start_time}','{self.students_end_time}','{self.time_id}')"


class departments(db.Model):
    "Adding the department page"
    department_id = db.Column(db.Integer,primary_key=True,nullable=False)   
    department_role = db.Column(db.String,nullable=False)

    def __repr__(self):
        return f"departments('{self.department_id}','{self.department_role}')"

class studentdepartment(db.Model):
    "Combine department id and students ID"
    combo_id = db.Column(db.Integer,primary_key=True)
    department_id = db.Column(db.Integer,ForeignKey(departments.department_id))
    students_id = db.Column(db.Integer,ForeignKey(students.students_id))

    def __repr__(self):
        return f"departmentstudents('{self.department_id}','{self.students_id}')"

我的route.py文件如下所示

def editdepartment(department_id):
    "Editing the already existing department"
    if request.method == 'GET':
        # Fetch the department name from the department table
        fetched_department_id = department_id
        getdepartment_name = department.query.filter(department.department_id==fetched_department_id).scalar()
        print(getdepartment_name,file=sys.stderr)
        #Fetch the student id based on the department id from the studentdeaprment  table
        get_department_details = departmentstudent.query.all()

        print(get_department_details,file=sys.stderr)
        return render_template("edit-departments.html")    

1 个答案:

答案 0 :(得分:1)

我不了解学生部门中Student_id和Department_id的重复字段。如果有关系  -学生与学生部门之间  -系与学生系之间 所需的代码将如下所示:

class student (db.Model):
  student_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
  student_name = db.Column(db.String(45))
  studentdepartments = db.relationship('studentdepartment', backref='student', 
     lazy=True, cascade="delete") 
class department (db.Model):
   department_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
   department_name = db.Column(db.String(45), nullable=False)
   studentdepartments = db.relationship('studentdepartment', backref='department', 
       lazy=True, cascade="delete")
class studentdepartment (db.Model):
   combo_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
   student_id = db.Column(db.Integer, db.ForeignKey('student.student_id'))
   department_id = db.Column(db.Integer, db.ForeignKey('department.department_id'))

使用这样的模型,创建对象并请求学生部门是这样的:

s = student(student_name = "studentsamplename")
s1 = student(student_name = "studentsamplename1")
s2 = student(student_name = "studentsamplename2")
db.session.add(s)
db.session.add(s1)

d = department(department_name = "departmentsamplename")
d1 = department(department_name = "departmentsamplename1")

db.session.add(d)
db.session.add(d1)

sd = studentdepartment(student = s, department = d)
sd1 = studentdepartment(student = s1, department = d)
sd2 = studentdepartment(student = s2, department = d1)
db.session.add(sd)
db.session.add(sd1)
db.session.add(sd2)
db.session.commit()

studentdepartments = studentdepartment.query.all()

这将打印学生部门的列表。

打印输出 [studentdepartment('1','1','1'),studentpartment('2','1','2'),studentdepartment('3','2', '3')] (如果在模型中使用以下代码:

  def __repr__(self):
    return f"studentdepartment('{self.combo_id}', 
       '{self.department_id}','{self.student_id}')"