1
votes

Here my 3 tables are.

class StudentModel(db.Model):
    __tablename__="students"
    id=db.Column(db.Integer)
    prn=db.Column(db.Integer, primary_key=True)
    name=db.Column(db.String(50), nullable=False)
    mobile=db.Column(db.String(10), nullable=False)
    email=db.Column(db.String(150), nullable=False)
    department=db.Column(db.String(80), nullable=False)    
    classid=db.Column(db.Integer, db.ForeignKey('classes.id'))
    resultid=db.Column(db.Integer, db.ForeignKey('results.prn'))
    classes=db.relationship('ClassModel')
    results=db.relationship('ResultModel')

class ClassModel(db.Model):
    __tablename__="classes"
    id=db.Column(db.Integer, primary_key=True)
    classname=db.Column(db.String(80), unique=True, nullable=False)
    cc=db.Column(db.String(80), nullable=False)
    students=db.relationship('StudentModel', lazy='dynamic')

class ResultModel(db.Model):
    __tablename__="results"
    id=db.Column(db.Integer)
    prn=db.Column(db.Integer, primary_key=True)
    cgpa=db.Column(db.Float, nullable=False)
    students=db.relationship('StudentModel', lazy="dynamic")

SQL Query:

select name, mobile, email, department, classname, cc, cgpa form students s inner join classes c on s.classid=c.id inner join results r on r.prn=s.prn;

What will be the sqlalchemy query? Please help me.

2

2 Answers

0
votes

You can use Sqlitis library to convert plain SQL queries to SQLAlchemy expressions. It is usable from the command line or as a library.

Your SQL Query would result as the following SQLAlchemy expression:

select([text('name'), text('mobile'), text('email'), text('department'), text('classname'), text('cc'), text('cgpa')]).select_from(students.join(classes, s.c.classid == c.c.id).join(results, r.c.prn == s.c.prn))

Please thumb me up if I've helped somehow =)

0
votes
db.session.query(StudentModel.name,StudentModel.mobile,StudentModel.email,
                 StudentModel.department,ClassModel.cc,ResultModel.cgpa)\
          .join(ClassModel)\
          .join(ResultModel)\
          .order_by(StudentModel.name,StudentModel.department).all()

I think you have the wrong column set as the primary key in the ResultModel table. Should it not be the id column?