CaffeinatedMike
CaffeinatedMike

Reputation: 1607

Is there a way in SQLAlchemy to proxy a JSON field of key/value pairs to act as individual columns?

My situation is similar to that of the Vertical Attribute Mapping examples covered in the SQLAlchemy documentation. However, the column names and values are stored in a JSON field as a dictionary. The types of each column are stored in another table with another JSON field (key/value, key being the field name and value being the field type).

Is it possible to create an association proxy that would treat the kwargs field's dictionary as individual, query-able columns?

class MainClass(db.Model):
    __tablename__ = "main_class"
    id = db.Column(db.Integer, primary_key=True)
    ...
    # {"field_name1": "str", "field_name2": "int", "field_name3": "bool", "field_name4": "list"}
    valid_kwargs = db.Column(db.JSON, nullable=False, default=dict())

class ChildClass(db.Model):
    __tablename__ = "child_class"
    id = db.Column(db.Integer, primary_key=True)
    main_class_id = db.Column(db.Integer, db.ForeignKey("main_class.id"))
    ...
    # {"field_name1": "test", "field_name2": 1, "field_name3": False, "field_name4": ["a", "b", "c"]}
    kwargs = db.Column(db.JSON, nullable=False, default=dict())

Upvotes: 2

Views: 368

Answers (0)

Related Questions