SQL 炼金关系未链接 类
SQL Alchemy Relationship not linking classes
我有两个类:
class Country(Base):
__tablename__ = 'country'
country_id = Column(BigInteger, primary_key=True)
cities = relationship('city',back_populates='country')
class City(Base):
__tablename__='city'
country_id = Column(BigInteger,ForeignKey('country.country_id'))
country = relationship("country",back_populates='cities')
city_id = Column(BigInteger,primary_key=True)
x=Column(BigInteger)
y=Column(BigInteger)
现在,当我创建国家/地区对象时:
c1 = City(x=0,y=0)
c2 = City(x=5,y=2)
country = Country(cities = [c1,c2])
并致电
print(c1.country_id)
None
我该如何解决这个问题?
谢谢!
下面的脚本有效。问题中有两个变化
- 更改关系以匹配文档中的基本 one-to-many relationship
- 将实例添加到会话并刷新以从数据库中获取 ID
- 将主键从
BigInteger
更改为 Integer
在 SQLite 上需要将主键的类型从 BigInteger
更改为 Integer
,但在 MariaDB (MySQL) 或 Postgresql 上则不需要。
import sqlalchemy as sa
from sqlalchemy import orm
Base = orm.declarative_base()
class Country(Base):
__tablename__ = "country"
country_id = sa.Column(sa.Integer, primary_key=True)
cities = orm.relationship("City")
class City(Base):
__tablename__ = "city"
country_id = sa.Column(sa.Integer, sa.ForeignKey("country.country_id"))
city_id = sa.Column(sa.Integer, primary_key=True)
x = sa.Column(sa.Integer)
y = sa.Column(sa.Integer)
engine = sa.create_engine("sqlite://", echo=True)
Base.metadata.create_all(engine)
session = orm.Session(engine)
c1 = City(x=0, y=0)
c2 = City(x=5, y=2)
country = Country(cities=[c1, c2])
session.add(country)
session.flush()
print(c1.country_id)
我有两个类:
class Country(Base):
__tablename__ = 'country'
country_id = Column(BigInteger, primary_key=True)
cities = relationship('city',back_populates='country')
class City(Base):
__tablename__='city'
country_id = Column(BigInteger,ForeignKey('country.country_id'))
country = relationship("country",back_populates='cities')
city_id = Column(BigInteger,primary_key=True)
x=Column(BigInteger)
y=Column(BigInteger)
现在,当我创建国家/地区对象时:
c1 = City(x=0,y=0)
c2 = City(x=5,y=2)
country = Country(cities = [c1,c2])
并致电
print(c1.country_id)
None
我该如何解决这个问题? 谢谢!
下面的脚本有效。问题中有两个变化
- 更改关系以匹配文档中的基本 one-to-many relationship
- 将实例添加到会话并刷新以从数据库中获取 ID
- 将主键从
BigInteger
更改为Integer
在 SQLite 上需要将主键的类型从 BigInteger
更改为 Integer
,但在 MariaDB (MySQL) 或 Postgresql 上则不需要。
import sqlalchemy as sa
from sqlalchemy import orm
Base = orm.declarative_base()
class Country(Base):
__tablename__ = "country"
country_id = sa.Column(sa.Integer, primary_key=True)
cities = orm.relationship("City")
class City(Base):
__tablename__ = "city"
country_id = sa.Column(sa.Integer, sa.ForeignKey("country.country_id"))
city_id = sa.Column(sa.Integer, primary_key=True)
x = sa.Column(sa.Integer)
y = sa.Column(sa.Integer)
engine = sa.create_engine("sqlite://", echo=True)
Base.metadata.create_all(engine)
session = orm.Session(engine)
c1 = City(x=0, y=0)
c2 = City(x=5, y=2)
country = Country(cities=[c1, c2])
session.add(country)
session.flush()
print(c1.country_id)