You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I want to access a relationship that exists on the child (in this example, "extras"), which is not on the parent.
When I query and find the child, the ORM returns the object as the parent type, making it impossible for me to access the relationship.
This is not happening when I use the terminal.
I'm unsure if this is an issue with my code, flask_sqlalchemy, or sqlalchemy. Guidance is welcome.
Example
class Parent (db.Model):
id = db.Column(db.Integer, primary_key=True, unique=True,)
first_name = db.Column(db.String(20))
last_name = db.Column(db.String(20))
class Child (Parent):
__tablename__ = "child"
__mapper_args__ = {"polymorphic_identity": "child"}
id = db.Column(db.Integer, db.ForeignKey("Parent.id"), primary_key=True)
extras = db.relationship('Extra', backref='Child', lazy=True)
class Extra(db.Model):
id = db.Column(db.Integer, unique=True, primary_key=True)
child_id = db.Column(db.Integer, db.ForeignKey("Child.id"), nullable=False)
text_of_extra = db.Column(db.String, nullable=False)
A simplified extract of my code looks roughly like:
the_child = Child.query.filter_by(id=child_id).first() # Simplified query demonstrating the point
print(f"child[ {the_child.id} ] has extras: {the_child.extras}")
The result is puzzling: AttributeError: 'Parent' object has no attribute 'extras'
Note that the object reported is 'Parent' despite the query being made explicitly on 'Child'.
However, from the CLI
>>> with app.app_context():
... the_child = Child.query.filter_by(id=child_id).first()
...
>>> the_child
<Child 001>
>>> the_child.extras
<sqlalchemy.orm.dynamic.AppenderQuery object at 0x000002649705F460>
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I have a child model than inherits from a parent.
I want to access a relationship that exists on the child (in this example, "extras"), which is not on the parent.
When I query and find the child, the ORM returns the object as the parent type, making it impossible for me to access the relationship.
This is not happening when I use the terminal.
I'm unsure if this is an issue with my code, flask_sqlalchemy, or sqlalchemy. Guidance is welcome.
Example
A simplified extract of my code looks roughly like:
The result is puzzling:
AttributeError: 'Parent' object has no attribute 'extras'
Note that the object reported is 'Parent' despite the query being made explicitly on 'Child'.
However, from the CLI
Beta Was this translation helpful? Give feedback.
All reactions