Two "one-to-one" references to same table in SQLAlchemy - sqlalchemy

Suppose I am modelling postal address changes. I'd like each AddressChange to have a before relationship to an Address, as well as an after relationship to another Address. And I'd like a reference back from the Address to the AddressChange it is associated with.
class AddressChange(Base):
__tablename__ = 'AddressChanges'
id = Column(Integer, primary_key=True)
before_id = Column(Integer, ForeignKey('Addresses.id'))
before = relationship('Address', foreign_keys=before_id, uselist=False,
back_populates='change')
after_id = Column(Integer, ForeignKey('Addresses.id'))
after = relationship('Address', foreign_keys=after_id, uselist=False,
back_populates='change')
class Address(Base):
__tablename__ = 'Addresses'
id = Column(Integer, primary_key=True)
street, city, etc = Column(String), Column(String), Column(String)
change = relationship('AddressChange')
However SQLAlchemy complains:
Could not determine join condition between parent/child tables on relationship Address.change - there are multiple foreign key paths linking the tables. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.
My Address does not have a foreign key reference to the parent table, and it's not clear to me why it should need one. If I add one, I get
Address.change and back-reference AddressChange.before are both of the same direction symbol('MANYTOONE'). Did you mean to set remote_side on the many-to-one side ?
Which is starting to get confusing, because the documentation for remote_side is for "self-referential relationships."

Thanks to #alex-grönholm for helping on #sqlalchemy.
This can be solved by adding a primaryjoin parameter to Address's side of the relationship to teach it how to map back to the parent AddressChange:
change = relationship('AddressChange', uselist=False,
viewonly=True,
primaryjoin=or_(
AddressChange.before_id == id,
AddressChange.after_id == id
))

Related

SQLAlchemy: Relationships based on third table

I'm trying to model following situation:
I need to set prices for groups of countries. So I have three entities:
class Zone:
zone = Column(Integer, primary_key=True)
class Country:
country = Column(String(2), primary_key=True)
zone = Column(Integer, ForeignKey('Zone.zone')
class Rate:
zone = Column(Integer, ForeignKey('Zone.zone')
rate = Column(Float)
Now I want to be able to access rates for a chosen Country. So I change my Country entity this way:
class Country:
country = Column(String(2), primary_key=True)
zone = Column(Integer, ForeignKey('Zone.zone')
rates = relationship('Rate', foreign_keys=[zone])
And I'm getting an error:
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Country.rates - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
Ok, I changed the Country entity:
class Country:
country = Column(String(2), primary_key=True)
zone = Column(Integer, ForeignKey('Zone.zone')
rates = relationship('Rate', primaryjoin="Country.zone == Rate.zone")
The error is changed:
sqlalchemy.exc.ArgumentError: Could not locate any relevant foreign key columns for primary join condition 'countries.zone = rates.zone' on relationship Country.rates. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or are annotated in the join condition with the foreign() annotation.
So the next version looks like that:
class Country:
country = Column(String(2), primary_key=True)
zone = Column(Integer, ForeignKey('Zone.zone')
rates = relationship('Rate', primaryjoin="foreign(Country.zone) == remote(Rate.zone)")
Surprisingly that partially worked. Partially because value of rates wasn't a list (by the way lazy='dynamic' caused an error as well) but a single (first) value. Somewhere I found a solution to that, which required change rather in Rate:
class Rate:
zone = Column(Integer, ForeignKey('Zone.zone')
rate = Column(Float)
__countries = relationship('Country',
primaryjoin="foreign(Rate.zone) == remote(Country.zone)",
backref='rates')
This finally worked. So here comes a question. The solution seems to be a bit cumbersome and doesn't rely on indexes, which might cause performance issues. Is there a better solution?

SQLAlchemy polymorphic Many-to-Many-Relation with Association Object

I have items of different type, say City, Country and Continent. And I have Labels. I want to be able to add multiple Labels to either City, Country and Continent objects. And each Label could have multiple items, too.
I cannot use table inheritance for defining City, Country and Continent here, since the models and their respective database tables are already existing and populated. Migrating the database to a different structure is impossible in my situation due to the size of the database. So I tried to make it with an Association Object, but I cannot figure out, how to create the relation from, say, Country to the Association in a way, that it only retrieves the lablables which have lablable_type = "country"
So, what I have looks like this:
Base = declarative_base()
class Lablable(Base):
__tablename__ = 'lablables'
label_id = db.Column(db.Integer, db.ForeignKey('labels.id'), primary_key=True)
lablable_id = db.Column(db.Integer)
lablable_type = db.Column(db.String(100))
labels = db.relationship("Label")
class Label(db.Model):
__tablename__ = "labels"
id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
caption = db.Column(db.String(200))
class Country(db.Model):
__tablename__ = "countries"
lablable_id = db.Column(db.Integer(), db.ForeignKey('lablables.id'))
lables = association_proxy('lablables', 'label',
creator=lambda x: Lablable(x=label))
How can I design my models to achieve what I want?

flask-sqlalchemy: how to define the 'comment' model (multi foreign keys referring to the same table)?

I'm working on a video sharing site, where users can comment under a video, or comment to someone else's comment. Here's my simplified user model and comment model:
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(MAX_USERNAME), unique=True)
comments = db.relationship('Comment', backref='replier', lazy='dynamic')
replied = db.relationship('Comment', backref='repliee', lazy='dynamic')
class Comment(db.Model):
__tablename__ = 'comments'
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text)
replier_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)
repliee_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)
video_id = db.Column(db.Integer, db.ForeignKey('videos.id'), index=True)
It prompts me with error:
Could not determine join condition between parent/child tables on relationship User.comments - there are multiple foreign key paths linking the tables. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table
Anybody can help? New to flask and sqlalchemy.
The comments and replied relationships don't know which foreign key column on Comment to use, since both replier_id and repliee_id refer to users.id.
So add the appropriate foreign_keys arguments to comments and replied:
comments = db.relationship('Comment', backref='replier', lazy='dynamic', foreign_keys='[Comment.replier_id]')
replied = db.relationship('Comment', backref='repliee', lazy='dynamic', foreign_keys='[Comment.repliee_id]')

sqlalchemy: multiple relationships (many to many via association object)

I'm trying to do this:
class Foo(Base):
id = Column(Integer, primary_key=True)
class Bar(Foo):
id = Column(Integer, primary_key=True)
class FooBarAssociation(Base):
foo_id = Column(Integer, ForeignKey('foo_table.id'))
bar_id = Column(Integer, ForeignKey('bar_table.id'))
foo = relationship(Foo, backref=...)
bar = relationship(Bar, backref=...)
...but I get errors like this:
Could not determine join condition between parent/child tables on relationship FooBarAssociation.foo. Specify a 'primaryjoin' expression. If this is a many-to-many relationship, 'secondaryjoin' is needed as well.
I've tried specifying foreign_keys and primary_join-s in the relationship declarations, but all for naught. Help? Is the inheritance of Bar from Foo messing with me?
thanks!
Following should work (exactly what the error tells: missing primaryjoin):
class FooBarAssociation(Base):
foo_id = Column(Integer, ForeignKey('foo_table.id'), primary_key = True, )
bar_id = Column(Integer, ForeignKey('bar_table.id'), ForeignKey('foo_table.id'), primary_key = True, )
foo = relationship(Foo, backref="bars", primaryjoin=(foo_id==Foo.id))
bar = relationship(Bar, backref="foos", primaryjoin=(bar_id==Bar.id))
As you can see, there are two foreign keys on the bar_id column. This could be required due to inheritance, or you might remove one. But if you do not store any other information apart of the many-to-many relationship, then you might consider Association Proxy instead.

SQLAlchemy recursive many-to-many relation

I've a case where I'm using one table to store user and group related datas. This column is called profile. So, basically this table is many-to-many table for the cases where one user is belonging in to many groups or there are many users in one group.
I'm a bit confused how it should be described...
Here's a simplified presentation of the class.
Entity relationship model
user_group_table = Table('user_group', metadata,
Column('user_id', Integer,ForeignKey('profiles.id',
onupdate="CASCADE", ondelete="CASCADE")),
Column('group_id', Integer, ForeignKey('profiles.id',
onupdate="CASCADE", ondelete="CASCADE"))
)
class Profile(Base)
__tablename__ = 'profiles'
id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(Unicode(16), unique=True) # This can be either user- / groupname
groups = relationship('Profile', secondary=user_group_table, backref = 'users')
users = relationship('Profile', secondary=user_group_table, backref = 'groups')
#Example of the usage:
user = Profile()
user.name = 'Peter'
salesGroup = Profile()
salesGroup.name = 'Sales'
user.groups.append(salesGroup)
salesGroup.users
>[peter]
First of all, I agree with Raven's comment that you should use separate tables for Users and Groups. The reason being that you might get some inconsistent data where a User might have other Users as its users relations, as well as you might have cycles in the relationship tree.
Having said that, to make the relationship work declare it as following:
...
class Profile(Base):
__tablename__ = 'profiles'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(Unicode(16), unique=True) # This can be either user- / groupname
groups = relationship('Profile',
secondary=user_group_table,
primaryjoin=user_group_table.c.user_id==id,
secondaryjoin=user_group_table.c.group_id==id,
backref='users')
...
Also see Specifying Alternate Join Conditions to relationship() documentation section.