ge4los
9/5/2016 - 9:42 AM

sqlalchemy hybrid

sqlalchemy hybrid

class Chalkboard(db.Model):
    """
    Resort announcement board.
    """
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    # content = db.Column(db.Text)
    resort_id = db.Column(db.Integer, db.ForeignKey('resort.id'),
      nullable=False)
    bg_image_url = db.Column(db.Text)
    active = db.Column(db.Boolean, default=True)
    resort = db.relationship('Resort', backref='chalkboard', uselist=False)

    @hybrid_property
    def content(self):
        return Translation.query.filter(Translation.resort_id==self.resort_id,
            Translation.object_id==self.id,
            Translation.object_type=='chalkboard.content',
            Translation.locale==session.locale).first.content

    @content.setter
    def content(self, value):
        t =  Translation.query.filter(Translation.resort_id==self.resort_id,
                Translation.object_id==self.id,
                Translation.object_type=='chalkboard.content',
                Translation.locale==session.locale).first
        if t:
            t.content = value
        else:
            create_new_translation_entry

class Translation(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    locale = db.Column(db.String(50), nullable=False)
    content = db.Column(db.Text, nullable=False)
    object_id = db.Column(db.Integer, nullable=False)
    object_type = db.Column(db.String(200), nullable=False)
    resort_id = db.Column(db.Integer, db.ForeignKey('resort.id'))