问题
I'm trying to implement the following with Flask+SQLAlchemy: I have two database models containing information about bee apiaries and bee hives. I would like to add feature to somehow connect both of them to Sensor model. Those can be attached to one of apiaries or one of bee hives. Here is what I have.
class Apiary(db.Model):
__tablename__ = 'apiary'
# ... fields ...
beehives = db.relationship("BeeHive", backref=db.backref('apiary', lazy='dynamic'), lazy='dynamic')
class BeeHive(db.Model)
__tablename__ = 'beehive'
# ... fields ...
apiary_id = db.Column(db.Integer(), db.ForeignKey('apiary.id'))
class SensorType(db.Model):
__tablename__ = 'sensor_type'
id = db.Column(db.Integer(), primary_key=True)
title = db.Column(db.Unicode(32), unique=True)
sensors = db.relationship('Sensor', backref=db.backref('sensor_type', lazy='dynamic'), lazy='dynamic')
class Sensor(db.Model):
__tablename__ = 'sensor'
id = db.Column(db.Integer(), primary_key=True)
serial = db.Column(UUID(), unique=True)
sensor_type_id = db.Column(db.Integer(), db.ForeignKey('sensor_type.id'))
readings = db.relationship('SensorReading', backref=db.backref('sensor', lazy='dynamic'), lazy='dynamic')
class SensorReading(db.Model):
__tablename__ = 'sensor_reading'
id = db.Column(db.BigInteger(), primary_key=True)
value = # TODO
timestamp = db.Column(db.DateTime(), default=db.func.now())
I was surfing through the internet, reading SQLAlchemy documentation and found something about "polymorphic loading". I have good feeling that this is probably what I was searching for, but don't know how to implement it in my case. I have seen similar thing in "Django world" and they call it "GenericForeignKey".
UPDATE: I have found SQLAlchemy examples about this type of association. Can anyone advice me which of those would be optimum approach? discriminator_on_related, generic_fk, table_per_association or table_per_related? Which of those will be the least headache in further expanding application? Cascading delete?
回答1:
After two days of experiments I have came to final conclusion. Examples have been taken from this source.
"Discriminator on association" (candidate for answer):
- (+) has backward reference
- (?) can have 1 parent object
- (-) complexity
"Generic Foreign Key":
- (+) low complexity
- (+) has backward reference
- (?) can have 1 parent object
- (-) programmer's code must take care of cascading actions
"table per association":
- (+) multiple parents
- (+) shared table stays intact
- (?) number of tables raises with number of associated tables
- (-) no backward reference
"table per related" (candidate for answer):
- (+) every associated object is in same table
- (+) can have multiple tables
- (-) associated objects are somehow separated for each foreign table
Answer: "Discriminator on association" as Sensor do not have ability of superposition and therefore no need for multiple parents.
来源:https://stackoverflow.com/questions/28261954/best-association-approach-to-connect-sensor-model-to-others