Dynamically generated field in SqlAlchemy model with Postgres

江枫思渺然 提交于 2019-12-11 07:58:33

问题


I want to create a table with a column for each hour of the day of Float type. How do I get rid of this verbose syntax:

from app import db

class HourlySchedule(db.Model):
    id = db.Column(
        db.Integer,
        primary_key=True
    )

    h0 = db.Column(db.Float, nullable=True)
    h1 = db.Column(db.Float, nullable=True)
    h2 = db.Column(db.Float, nullable=True)
    h3 = db.Column(db.Float, nullable=True)
    h4 = db.Column(db.Float, nullable=True)
    h5 = db.Column(db.Float, nullable=True)
    h6 = db.Column(db.Float, nullable=True)
    h7 = db.Column(db.Float, nullable=True)
    h8 = db.Column(db.Float, nullable=True)
    h9 = db.Column(db.Float, nullable=True)
    h10 = db.Column(db.Float, nullable=True)
    h11 = db.Column(db.Float, nullable=True)
    h12 = db.Column(db.Float, nullable=True)
    h13 = db.Column(db.Float, nullable=True)
    h14 = db.Column(db.Float, nullable=True)
    h15 = db.Column(db.Float, nullable=True)
    h16 = db.Column(db.Float, nullable=True)
    h17 = db.Column(db.Float, nullable=True)
    h18 = db.Column(db.Float, nullable=True)
    h19 = db.Column(db.Float, nullable=True)
    h20 = db.Column(db.Float, nullable=True)
    h21 = db.Column(db.Float, nullable=True)
    h22 = db.Column(db.Float, nullable=True)
    h23 = db.Column(db.Float, nullable=True)

Another question is how do I enforce checks on the values (e.g. 0 <= value <=1)?

As validation? Then how do i set validation neatly for 24 fields?

Can I instead add a check constraint with SqlAlchemy?


回答1:


The key here is to realize that a class block is just a block of code, so you can put loops in there:

class HourlySchedule(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    for i in range(24):
        locals()["h{}".format(i)] = db.Column(db.Float)

    @validates(*("h{}".format(i) for i in range(24)))
    def _validate(self, k, h):
        assert 0 <= h <= 1
        return h



回答2:


You may need to play around with the order of calling super().__init__(*args, **kwargs), but this should theoretically work.

As for validation, the good thing about the validates decorator is that it takes multiple column names, so we can achieve dynamic field creation and validation like so:

from app import db
from sqlalchemy.orm import validates


class HourlySchedule(db.Model):
    id = db.Column(
        db.Integer,
        primary_key=True
    )

    def __init__(self, *args, **kwargs):
        self.colstrings = []

        for hour in range(0, 24):
            colstring = "h{}".format(hour)
            setattr(self, colstring, db.Column(db.Float, nullable=True))
            self.colstrings.append(colstring)

        super().__init__(*args, **kwargs)

    @validates(*self.colstrings)
    def validate_hours(self, key, hour): 
        assert 0 < hour < 1
        return hour

One thing I'd like to note, however, is that this is actually greatly increases the complexity of a rather simple concept. Instead of hiding model details, which are meant to be verbose so devs can easily understand model > table mappings, it might make more sense to either list out every column, or to rethink how you're structuring your data.



来源:https://stackoverflow.com/questions/38550984/dynamically-generated-field-in-sqlalchemy-model-with-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!