0

I have a table representing a phone call and want to store that data

from app.db import db
from app.schema import ma

#db = SQLAlchemy()
class phoneCall(db.Model):
    __tablename__ = "phoneCalls"

    callerid = db.Column(db.String, primary_key=True)
    #from = db.Column(db.String)
    _from = db.Column("from", db.String)
    to = db.Column(db.String)
    duration = db.Column(db.Integer)

#ma = flask_marshmallow.Marshmallow()
class CallSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = phoneCall

Since from is a SQL keyword I can't directly use that as a column name. I tried setting it as

    _from = db.Column("from", db.String)

But when I return a phoneCall.query.all() I get the column name as _from. Additionally, I'm using a dict with the key as from to populate data into the table as well. How do get around this restricted keyword to accept input and also display the output of the query as

Input

call={'callid'='call34346346346',"duration":10 "from": "+1234", "to":"+1234"}

Expected output


[
    {
    "callerid": "call34346346346",
    "duration":10
    "from": "+1234",
    "to":"+1234"
    }
]

Actual output


[
    {
    "_from": "+1234",
    "callerid": "call34346346346",
    "duration":10
    "to":"+1234"
    }
]
  • If you want to change the column name in the database you will have to recreate the table or do a migration. For marshmallow, you need to use the `data_key` keyword as show in [this answer](https://stackoverflow.com/a/58414104/5320906) in the linked duplicate. – snakecharmerb Feb 12 '23 at 10:46
  • I'm creating the database and the table, so there's no need for migration. The data_key (and other suggestions in that answer) didn't work. I suspect it's because I'm using SQLAlchemyAutoSchema ```_from = fields.String(data_key="from") TypeError: Raw.__init__() got an unexpected keyword argument 'data_key'``` – user14530855 Feb 12 '23 at 20:53
  • [This](https://pastebin.com/hJxQN70j) worked for me (it uses vanilla SQLAlchemy, but that shouldn't make any difference). – snakecharmerb Feb 12 '23 at 21:14
  • 1
    Ah. Thanks for writing that up. I adopted that to `SQLAlchemyAutoSchema` and I think I was initially doing the indentation wrong. Once that was fixed the column name is showing up correctly. Thank you! – user14530855 Feb 12 '23 at 21:26

0 Answers0