Flask SQLAlchemy: Child table with multiple parents? - python

I'm new to flask_sqlalchemy, and while I understand how the one-to-many, and many-to-many relationships work, I'm struggling to understand how I can apply them to my specific data types. I have the following three tables: TeamStat, PlayerStat, and Stat which are loosely described as follows
class PlayerStat(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.DateTime, nullable=False, default=datetime.datetime)
player_id = db.Column(db.Integer, db.ForeignKey('player.player_id'), nullable=False)
class TeamStat(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.DateTime, nullable=False, default=datetime.datetime)
team_id = db.Column(db.Integer, db.ForeignKey('team.team_id'), nullable=False)
class Stat(db.Model):
id = db.Column(db.Integer, primary_key=True)
value = db.Column(db.String(80), nullable=False)
Since Stat is a generic table type, I would like to use it by both the PlayerStat table (for individual player stats), as well as the TeamStat table (as a sum of the stats for all players on a team). Can someone help me understand how I can refer one child table to multiple parent tables in this fashion?

Use association tables to bridge your stat table to your players and team tables. This example is pretty close to what you are already doing, except the date column is moved on to the stat record table and I've replaced your PlayerStat and TeamStat objects with unmapped tables.
I've assumed you have two ORM classes, Player and Team (not Flask-SQLAlchemy sorry but concept remains the same):
plr_stat_assc = Table('plr_stat_assc', Base.metadata,
Column('player_id', Integer, ForeignKey('player.id')),
Column('stat_id', Integer, ForeignKey('stat.id'))
)
team_stat_assc = Table('team_stat_assc', Base.metadata,
Column('team_id', Integer, ForeignKey('team.id')),
Column('stat_id', Integer, ForeignKey('stat.id'))
)
class Player(Base):
__tablename__ = 'player'
id = Column(Integer, primary_key=True)
stats = relationship("Stat", secondary=plr_stat_assc)
class Team(Base):
__tablename__ = 'team'
id = Column(Integer, primary_key=True)
stats = relationship("Stat", secondary=team_stat_assc)
class Stat(Base):
__tablename__ = 'stat'
id = Column(Integer, primary_key=True)
date = Column(DateTime, nullable=False, default=datetime.datetime)
value = Column(String(80), nullable=False)

Related

SqlAlchemy - Nested relationship loading behaviour

I use SqlAlchemy to manage queries with my database, but i have a problem.
I have 3 Tables defined here:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
orders = relationship("Order", backref=backref("payer", uselist=True, lazy='dynamic'), foreign_keys="Order.user_id", order_by="desc(Order.date)")
gifts = relationship("Order", backref=backref("receiver", uselist=False), foreign_keys="Order.user_target_id", order_by="desc(Order.date)")
class Order(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
user_target_id = db.Column(db.Integer, db.ForeignKey('user.id'))
partner_id = db.Column(db.Integer, db.ForeignKey('partner.id'))
class Partner(db.Model):
id = db.Column(db.Integer, primary_key=True)
orders = relationship("Order", backref=backref("partner", uselist=False))
I would like to get all the "gifts" for a user, and for each gift (an Order object) i expect to get the 'payer', 'receiver' and 'partner' relations filled.
I am really new with SqlAlchemy so maybe that i have badly configured my relationships.
Can somebody help me ?

SQLAlchemy different tables for relationship?

Suppose I have the following tables/relationships defined:
class Post(Base):
__table_name__ = "post"
id = Column(Integer, primary_key=True)
text = Column(String(100))
class Comment(Base):
__table_name__ = "comment"
id = Column(Integer, primary_key=True)
post_id = Column(Integer, ForeignKey("post.id"), nullable=False)
text = Column(String(100))
Now, I want to have notifications of events, like "You were tagged in a comment" or "you were tagged in a post". Is there some way to have a foreign key relationship in SQLAlchemy that can point to either a comment or a post (or several other tables in reality)? Something like:
class Notification(Base):
__table_name__ = "notification"
id = Column(Integer, primary_key=True)
target = relationship(??either post or comment??)
user_id = Column(Integer, ForeignKey("users.id")
created_date = Column(Datetime, default=datetime.utcnow)
I suppose you could just put foreign keys to all the different types and make all but one null, but that seems ugly. I'd also rather not have multiple tables for each type of notification; as in comment_notification and post_notification. Any ideas?

Generated queries contain redundant products?

I have rather simple models like these:
TableA2TableB = Table('TableA2TableB', Base.metadata,
Column('tablea_id', BigInteger, ForeignKey('TableA.id')),
Column('tableb_id', Integer, ForeignKey('TableB.id')))
class TableA(Base):
__tablename__ = 'TableA'
id = Column(BigInteger, primary_key=True)
infohash = Column(String, unique=True)
url = Column(String)
tablebs = relationship('TableB', secondary=TableA2TableB, backref='tableas')
class TableB(Base):
__tablename__ = 'TableB'
id = Column(Integer, primary_key=True)
url = Column(String, unique=True)
However, sqla generates queries like
SELECT "TableB".id, "TableB".url AS "TableB_url" FROM "TableB", "TableA2TableB"
WHERE "TableA2TableB".tableb_id = "TableB".id AND "TableA2TableB".tablea_id = 408997;
But why is there a cartesian product in the query when the attributes selected are those in TableB? TableA2TableB shouldn't be needed.
Thanks
As it is right now, there is a backref relationship in TableB (tableas) and it's loaded because the default loading mode is set to select.
You may want to change the TableA.tablebs to
tablebs = relationship('TableB', secondary=TableA2TableB, backref='tableas', lazy="dynamic")

sqlalchemy constraint in models inheritance

I have two simple models:
class Message(Backend.instance().get_base()):
__tablename__ = 'messages'
id = Column(Integer, primary_key=True, autoincrement=True)
sender_id = Column(Integer, ForeignKey('users.id'))
content = Column(String, nullable=False)
class ChatMessage(Message):
__tablename__ = 'chat_messages'
id = Column(Integer, ForeignKey('messages.id'), primary_key=True)
receiver_id = Column(Integer, ForeignKey('users.id'))
How to define constraint sender_id!=receiver_id?
This doesn't seem to work with joined table inheritance, I've tried and it complains that the column sender_id from Message doesn't exist when creating the constraint in ChatMessage.
This complaint makes sense, since sender_id wouldn't be in the same table as receiver_id when the tables are created, so the foreign key relationship would need to be followed to check the constraint.
One option is to make ChatMessage a single table.
Use CheckConstraint, placed in table args.
class ChatMessage(Base):
__tablename__ = 'chat_messages'
id = sa.Column(sa.Integer, primary_key=True)
sender_id = sa.Column(sa.Integer, sa.ForeignKey(User.id))
receiver_id = sa.Column(sa.Integer, sa.ForeignKey(User.id))
content = sa.Column(sa.String, nullable=False)
__table_args__ = (
sa.CheckConstraint(receiver_id != sender_id),
)

SQLAlchemy Polymorphic Loading

I've this model in SQLAlchemy:
class User(Base):
__tablename = 'users'
id = Column(Integer, primary_key=True, autoincrement=True)
type = Column(Text, nullable=False)
user_name = Column(Text, unique=True, nullable=False)
__mapper_args__ = {'polymorphic_on': type}
class Client(User):
__tablename__ = 'clients'
__mapper_args__ = {'polymorphic_identity': 'client'}
id = Column(Integer, ForeignKey('users.id'), primary_key=True)
client_notes = Column(Text)
This is a joined table inheritance. The problem is when I'm querying User:
self.session.query(User).all()
all I get is records from clients, while what I want is all record on User without Client. How do I solve this problem?
Edit: I'm using SQLAlchemy 0.7.4 and Pyramid 1.3a3
session.query(User) does not perform any filtering based on the value of type column.
However, the SQL SELECT statement it generates selects only data from the users table (unless with_polymorphic(...) is used).
But you can add the filter explicitely to achive the desired result:
session.query(User).filter(User.type=='user').all()

Categories

Resources