SQLAlchemy - Return filtered table AND corresponding foreign table valuesAdd a column with a default value to an existing table in SQL ServerHow to return multiple values from a function?How can I list all foreign keys referencing a given table in SQL Server?What's the difference between filter and filter_by in SQLAlchemy?Finding duplicate values in a SQL tableSQLAlchemy generating query in loop with containsRelationship between two tables one with 2 foreign keys in flask-sqlalchemyFlask-msearch python , adding msearch on many to many tableHow to do FLASK SQLALCHEMY query for Association TableSQLAlchemy 3 table join and filter odd behavior

Given this phrasing in the lease, when should I pay my rent?

Are Captain Marvel's powers affected by Thanos breaking the Tesseract and claiming the stone?

What is the meaning of the following sentence?

Does the Crossbow Expert feat's extra crossbow attack work with the reaction attack from a Hunter ranger's Giant Killer feature?

Usage of an old photo with expired copyright

Has the laser at Magurele, Romania reached a tenth of the Sun's power?

In One Punch Man, is King actually weak?

Why is participating in the European Parliamentary elections used as a threat?

How can I, as DM, avoid the Conga Line of Death occurring when implementing some form of flanking rule?

Isometric embedding of a genus g surface

Sigmoid with a slope but no asymptotes?

Do you waste sorcery points if you try to apply metamagic to a spell from a scroll but fail to cast it?

Sound waves in different octaves

How would you translate "more" for use as an interface button?

Pre-Employment Background Check With Consent For Future Checks

How were servants to the Kaiser of Imperial Germany treated and where may I find more information on them

How can I safely use "Thalidomide" in my novel while respecting the trademark?

Can you identify this lizard-like creature I observed in the UK?

Personal or impersonal in a technical resume

Proving an identity involving cross products and coplanar vectors

Ways of geometrical multiplication

How to leave product feedback on macOS?

If Captain Marvel (MCU) were to have a child with a human male, would the child be human or Kree?

Should I assume I have passed probation?



SQLAlchemy - Return filtered table AND corresponding foreign table values


Add a column with a default value to an existing table in SQL ServerHow to return multiple values from a function?How can I list all foreign keys referencing a given table in SQL Server?What's the difference between filter and filter_by in SQLAlchemy?Finding duplicate values in a SQL tableSQLAlchemy generating query in loop with containsRelationship between two tables one with 2 foreign keys in flask-sqlalchemyFlask-msearch python , adding msearch on many to many tableHow to do FLASK SQLALCHEMY query for Association TableSQLAlchemy 3 table join and filter odd behavior













1















I have the following SQLAlchemy mapped classes:



class ShowModel(db.Model):
__tablename__ = 'shows'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
episodes = db.relationship('EpisodeModel', backref='episode', lazy='dynamic')

class EpisodeModel(db.Model):
__tablename__ = 'episodes'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200))
show_id = db.Column(db.Integer, db.ForeignKey('shows.id'))
info = db.relationship('InfoModel', backref='episode', lazy='dynamic')

class InfoModel(db.Model):
__tablename__ = 'info'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
episode_id = db.Column(db.Integer, db.ForeignKey('episodes.id'))


I'm trying and failing to figure out how to perform a query that searches the info table for a specific name column value AND then return the shows and episodes table rows that are associated with it.



Using the following query allows me to return the specific info row that matches the filter_by(name=name) query



InfoModel.query.filter_by(name=name).all()))


But I am really struggling to figure out how to also get the values of the corresponding foreign key rows that have a relationship with the specific info row. Is there a proper way to do this with the join statement or something similar? Thank you very much for any help on this, as I'm still trying to get the hang of working with SQL databases, and databases in general.



Edit -



If, for example, I use the query InfoModel.query.filter_by(name="ShowName1").all())), my json() representation returns




"name": "InfoName1",
"id": 1,
"episode_id": 1



But I'm also wanting to return the associated foreign table values so that my json() representation returns -




"name": "ShowName1",
"id": 1,
"episodes":

"name": "EpisodeName1",
"id": 1,
"show_id": 1
"info":

"name": "InfoName1",
"id": 1,
"episode_id": 1

,



And I apologize for fumbling over my use of jargon here, making my question appear more complicated than it is.










share|improve this question
























  • Can you clarify what you want the query to return? Like, which rows from EpisodeModel and ShowModel are supposed to be returned?

    – Sam
    Mar 7 at 22:48











  • Also, is there a reason you need lazyload set to dynamic as opposed to joined? Joined might get you what you want.

    – Sam
    Mar 7 at 22:51











  • I edited the post to hopefully better explain what I'm trying to return. And I'm embarrassed to say that I'm not 100 percent sure why I have lazyload set to dynamic instead of joined, and now that you mention it, I'll be diligently studying the differences between the two. Thank you!

    – Sean
    Mar 7 at 23:26















1















I have the following SQLAlchemy mapped classes:



class ShowModel(db.Model):
__tablename__ = 'shows'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
episodes = db.relationship('EpisodeModel', backref='episode', lazy='dynamic')

class EpisodeModel(db.Model):
__tablename__ = 'episodes'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200))
show_id = db.Column(db.Integer, db.ForeignKey('shows.id'))
info = db.relationship('InfoModel', backref='episode', lazy='dynamic')

class InfoModel(db.Model):
__tablename__ = 'info'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
episode_id = db.Column(db.Integer, db.ForeignKey('episodes.id'))


I'm trying and failing to figure out how to perform a query that searches the info table for a specific name column value AND then return the shows and episodes table rows that are associated with it.



Using the following query allows me to return the specific info row that matches the filter_by(name=name) query



InfoModel.query.filter_by(name=name).all()))


But I am really struggling to figure out how to also get the values of the corresponding foreign key rows that have a relationship with the specific info row. Is there a proper way to do this with the join statement or something similar? Thank you very much for any help on this, as I'm still trying to get the hang of working with SQL databases, and databases in general.



Edit -



If, for example, I use the query InfoModel.query.filter_by(name="ShowName1").all())), my json() representation returns




"name": "InfoName1",
"id": 1,
"episode_id": 1



But I'm also wanting to return the associated foreign table values so that my json() representation returns -




"name": "ShowName1",
"id": 1,
"episodes":

"name": "EpisodeName1",
"id": 1,
"show_id": 1
"info":

"name": "InfoName1",
"id": 1,
"episode_id": 1

,



And I apologize for fumbling over my use of jargon here, making my question appear more complicated than it is.










share|improve this question
























  • Can you clarify what you want the query to return? Like, which rows from EpisodeModel and ShowModel are supposed to be returned?

    – Sam
    Mar 7 at 22:48











  • Also, is there a reason you need lazyload set to dynamic as opposed to joined? Joined might get you what you want.

    – Sam
    Mar 7 at 22:51











  • I edited the post to hopefully better explain what I'm trying to return. And I'm embarrassed to say that I'm not 100 percent sure why I have lazyload set to dynamic instead of joined, and now that you mention it, I'll be diligently studying the differences between the two. Thank you!

    – Sean
    Mar 7 at 23:26













1












1








1








I have the following SQLAlchemy mapped classes:



class ShowModel(db.Model):
__tablename__ = 'shows'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
episodes = db.relationship('EpisodeModel', backref='episode', lazy='dynamic')

class EpisodeModel(db.Model):
__tablename__ = 'episodes'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200))
show_id = db.Column(db.Integer, db.ForeignKey('shows.id'))
info = db.relationship('InfoModel', backref='episode', lazy='dynamic')

class InfoModel(db.Model):
__tablename__ = 'info'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
episode_id = db.Column(db.Integer, db.ForeignKey('episodes.id'))


I'm trying and failing to figure out how to perform a query that searches the info table for a specific name column value AND then return the shows and episodes table rows that are associated with it.



Using the following query allows me to return the specific info row that matches the filter_by(name=name) query



InfoModel.query.filter_by(name=name).all()))


But I am really struggling to figure out how to also get the values of the corresponding foreign key rows that have a relationship with the specific info row. Is there a proper way to do this with the join statement or something similar? Thank you very much for any help on this, as I'm still trying to get the hang of working with SQL databases, and databases in general.



Edit -



If, for example, I use the query InfoModel.query.filter_by(name="ShowName1").all())), my json() representation returns




"name": "InfoName1",
"id": 1,
"episode_id": 1



But I'm also wanting to return the associated foreign table values so that my json() representation returns -




"name": "ShowName1",
"id": 1,
"episodes":

"name": "EpisodeName1",
"id": 1,
"show_id": 1
"info":

"name": "InfoName1",
"id": 1,
"episode_id": 1

,



And I apologize for fumbling over my use of jargon here, making my question appear more complicated than it is.










share|improve this question
















I have the following SQLAlchemy mapped classes:



class ShowModel(db.Model):
__tablename__ = 'shows'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
episodes = db.relationship('EpisodeModel', backref='episode', lazy='dynamic')

class EpisodeModel(db.Model):
__tablename__ = 'episodes'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200))
show_id = db.Column(db.Integer, db.ForeignKey('shows.id'))
info = db.relationship('InfoModel', backref='episode', lazy='dynamic')

class InfoModel(db.Model):
__tablename__ = 'info'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
episode_id = db.Column(db.Integer, db.ForeignKey('episodes.id'))


I'm trying and failing to figure out how to perform a query that searches the info table for a specific name column value AND then return the shows and episodes table rows that are associated with it.



Using the following query allows me to return the specific info row that matches the filter_by(name=name) query



InfoModel.query.filter_by(name=name).all()))


But I am really struggling to figure out how to also get the values of the corresponding foreign key rows that have a relationship with the specific info row. Is there a proper way to do this with the join statement or something similar? Thank you very much for any help on this, as I'm still trying to get the hang of working with SQL databases, and databases in general.



Edit -



If, for example, I use the query InfoModel.query.filter_by(name="ShowName1").all())), my json() representation returns




"name": "InfoName1",
"id": 1,
"episode_id": 1



But I'm also wanting to return the associated foreign table values so that my json() representation returns -




"name": "ShowName1",
"id": 1,
"episodes":

"name": "EpisodeName1",
"id": 1,
"show_id": 1
"info":

"name": "InfoName1",
"id": 1,
"episode_id": 1

,



And I apologize for fumbling over my use of jargon here, making my question appear more complicated than it is.







python sql sqlalchemy






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 23:24







Sean

















asked Mar 7 at 22:10









SeanSean

608




608












  • Can you clarify what you want the query to return? Like, which rows from EpisodeModel and ShowModel are supposed to be returned?

    – Sam
    Mar 7 at 22:48











  • Also, is there a reason you need lazyload set to dynamic as opposed to joined? Joined might get you what you want.

    – Sam
    Mar 7 at 22:51











  • I edited the post to hopefully better explain what I'm trying to return. And I'm embarrassed to say that I'm not 100 percent sure why I have lazyload set to dynamic instead of joined, and now that you mention it, I'll be diligently studying the differences between the two. Thank you!

    – Sean
    Mar 7 at 23:26

















  • Can you clarify what you want the query to return? Like, which rows from EpisodeModel and ShowModel are supposed to be returned?

    – Sam
    Mar 7 at 22:48











  • Also, is there a reason you need lazyload set to dynamic as opposed to joined? Joined might get you what you want.

    – Sam
    Mar 7 at 22:51











  • I edited the post to hopefully better explain what I'm trying to return. And I'm embarrassed to say that I'm not 100 percent sure why I have lazyload set to dynamic instead of joined, and now that you mention it, I'll be diligently studying the differences between the two. Thank you!

    – Sean
    Mar 7 at 23:26
















Can you clarify what you want the query to return? Like, which rows from EpisodeModel and ShowModel are supposed to be returned?

– Sam
Mar 7 at 22:48





Can you clarify what you want the query to return? Like, which rows from EpisodeModel and ShowModel are supposed to be returned?

– Sam
Mar 7 at 22:48













Also, is there a reason you need lazyload set to dynamic as opposed to joined? Joined might get you what you want.

– Sam
Mar 7 at 22:51





Also, is there a reason you need lazyload set to dynamic as opposed to joined? Joined might get you what you want.

– Sam
Mar 7 at 22:51













I edited the post to hopefully better explain what I'm trying to return. And I'm embarrassed to say that I'm not 100 percent sure why I have lazyload set to dynamic instead of joined, and now that you mention it, I'll be diligently studying the differences between the two. Thank you!

– Sean
Mar 7 at 23:26





I edited the post to hopefully better explain what I'm trying to return. And I'm embarrassed to say that I'm not 100 percent sure why I have lazyload set to dynamic instead of joined, and now that you mention it, I'll be diligently studying the differences between the two. Thank you!

– Sean
Mar 7 at 23:26












1 Answer
1






active

oldest

votes


















1














Because you have lazy loading enabled, the joined tables will only be set when they are accessed. What you can do is force a join. Something like the following should work for you:



shows = session.query(ShowModel)
.join(EpisodeModel)
.join(InfoModel)
.filter(ShowModel.name == "foo")
.all()


You can also change your load configuration to be "eager", or any number of other options. I don't like to do this by default though, as it makes for accidentally expensive queries: https://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55053618%2fsqlalchemy-return-filtered-table-and-corresponding-foreign-table-values%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Because you have lazy loading enabled, the joined tables will only be set when they are accessed. What you can do is force a join. Something like the following should work for you:



    shows = session.query(ShowModel)
    .join(EpisodeModel)
    .join(InfoModel)
    .filter(ShowModel.name == "foo")
    .all()


    You can also change your load configuration to be "eager", or any number of other options. I don't like to do this by default though, as it makes for accidentally expensive queries: https://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html






    share|improve this answer



























      1














      Because you have lazy loading enabled, the joined tables will only be set when they are accessed. What you can do is force a join. Something like the following should work for you:



      shows = session.query(ShowModel)
      .join(EpisodeModel)
      .join(InfoModel)
      .filter(ShowModel.name == "foo")
      .all()


      You can also change your load configuration to be "eager", or any number of other options. I don't like to do this by default though, as it makes for accidentally expensive queries: https://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html






      share|improve this answer

























        1












        1








        1







        Because you have lazy loading enabled, the joined tables will only be set when they are accessed. What you can do is force a join. Something like the following should work for you:



        shows = session.query(ShowModel)
        .join(EpisodeModel)
        .join(InfoModel)
        .filter(ShowModel.name == "foo")
        .all()


        You can also change your load configuration to be "eager", or any number of other options. I don't like to do this by default though, as it makes for accidentally expensive queries: https://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html






        share|improve this answer













        Because you have lazy loading enabled, the joined tables will only be set when they are accessed. What you can do is force a join. Something like the following should work for you:



        shows = session.query(ShowModel)
        .join(EpisodeModel)
        .join(InfoModel)
        .filter(ShowModel.name == "foo")
        .all()


        You can also change your load configuration to be "eager", or any number of other options. I don't like to do this by default though, as it makes for accidentally expensive queries: https://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 11 at 17:25









        thejohnbackesthejohnbackes

        898615




        898615





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55053618%2fsqlalchemy-return-filtered-table-and-corresponding-foreign-table-values%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme