1

I've created a database using "flask-sqlalchemy".

There are two tables:1-University and 2-Field

one University can have many Field(s) so here we have a one-to-many relation. So when we query University it also returns a list of Field(s) for each row of the University table.The code is in below:

class University(db.Model):
    name = db.Column(db.String(120), index=True, unique=True, primary_key=True)
    country = db.Column(db.String(128))
    fields = db.relationship('Field', lazy='dynamic')
    ...
    ...

class Field(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    study = db.Column(db.String(256), nullable=False)
    grade = db.Column(db.String(256))
    university_name = db.Column(db.String(256), db.ForeignKey('university.name'))

my question is:I want to query the University and also It's relation at the same time so that the result would be a University object which contains only one specific Field object with it(not a list of all the Field(s) related to that one university object)so here after I filter the University I'm then filtering(querying)It's relation

I have 3parameters for the query,one is in University and the other two are for It's relation:

country_param = 'usa'
grade_param = 'master'
study_param = 'electronics'

I'm struggling and reading sqlalchemy docs,flask-sqlalchemy docs for two days and I've read and tried many similar questions in stack-over-flow and nothing worked.

plus many different combinations like

existing = University.query.join(University.fields).filter(University.country == 'usa',
                                                           Field.grade == 'phd').first()

or

    a = Field.query.with_parent(u).filter(Field.grade == 'master').all()

I've tried but nothing works.

-Thanks for reading my question and helping me

davidism
  • 121,510
  • 29
  • 395
  • 339
N_mirzaee
  • 11
  • 2

0 Answers0