SQLAlchemy declarative one-to-many not defined error

2024/10/3 8:17:58

I'm trying to figure how to define a one-to-many relationship using SQLAlchemy's declarative ORM, and trying to get the example to work, but I'm getting an error that my sub-class can't be found (naturally, because it's declared later...)

InvalidRequestError: When initializing mapper Mapper|Parent|parent, expression 'Child' failed to locate a name ("name 'Child' is not defined"). If this is a class name, consider adding this relationship() to the class after both dependent classes have been defined.

But how do I define this, without the error?

The code:

from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from dev.historyMeta import VersionedMeta, VersionedListenerglobal engine, Base, Session
engine = create_engine('mysql+mysqldb://user:pass@localhost:3306/testdb', pool_recycle=3600)
Base = declarative_base(bind=engine, metaclass=VersionedMeta)
Session = sessionmaker(extension=VersionedListener())class Parent(Base):__tablename__ = 'parent'id = Column(Integer, primary_key=True)children = relationship("Child", backref="parent")class Child(Base):__tablename__ = 'child'id = Column(Integer, primary_key=True)parent_id = Column(Integer, ForeignKey('parent.id'))Base.metadata.create_all()
Answer

Here's how I do it:

from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationshipengine = create_engine('sqlite://', echo=True)
Base = declarative_base(bind=engine)
Session = sessionmaker(bind=engine)class Parent(Base):__tablename__ = 'parent'id = Column(Integer, primary_key=True)class Child(Base):__tablename__ = 'child'id = Column(Integer, primary_key=True)parent_id = Column(Integer, ForeignKey('parent.id'))parent = relationship(Parent, backref='children')Base.metadata.create_all()
https://en.xdnf.cn/q/70748.html

Related Q&A

Convert numpy.array object to PIL image object

I have been trying to convert a numpy array to PIL image using Image.fromarray but it shows the following error. Traceback (most recent call last): File "C:\Users\Shri1008 SauravDas\AppData\Loc…

Scheduling celery tasks with large ETA

I am currently experimenting with future tasks in celery using the ETA feature and a redis broker. One of the known issues with using a redis broker has to do with the visibility timeout:If a task isn’…

How to read out scroll wheel info from /dev/input/mice?

For a home robotics project I need to read out the raw mouse movement information. I partially succeeded in this by using the python script from this SO-answer. It basically reads out /dev/input/mice a…

Tell me why this does not end up with a timeout error (selenium 2 webdriver)?

from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWaitbrowser = webdriver.Firefox()browser.get("http://testsite.com")element = WebDriverWait(browser, 10).until…

PEP 8: comparison to True should be if cond is True: or if cond:

PyCharm is throwing a warning when I do np.where(temp == True)My full code:from numpy import where, arraya = array([[0.4682], [0.5318]]) b = array([[0.29828851, 0., 0.28676873, 0., 0., 0., 0., 0.288014…

Getting the title of youtube video in pytube3?

I am trying to build an app to download YouTube videos in python using pytube3. But I am unable to retrieve the title of the video. Here goes my code: from pytube import YouTube yt = YouTube(link) prin…

pandas - concat with columns of same categories turns to object

I want to concatenate two dataframes with category-type columns, by first adding the missing categories to each column.df = pd.DataFrame({"a": pd.Categorical(["foo", "foo"…

Python convert Excel File (xls or xlsx) to/from ODS

Ive been scouring the net to find a Python library or tool that can converts an Excel file to/from ODS format, but havent been able to come across anything. I need the ability to input and output data …

Select pandas frame rows based on two columns values

I wish to select some specific rows based on two column values. For example:d = {user : [1., 2., 3., 4] ,item : [5., 6., 7., 8.],f1 : [9., 16., 17., 18.], f2:[4,5,6,5], f3:[4,5,5,8]} df = pd.DataFrame(…

Using scipy sparse matrices to solve system of equations

This is a follow up to How to set up and solve simultaneous equations in python but I feel deserves its own reputation points for any answer.For a fixed integer n, I have a set of 2(n-1) simultaneous e…