0

My problem: I am iterating through raw data to update a DB Table. Each item in the raw data is linked to one column (out of 19 different visa categories) in the DB Table. Is it possible to dynamically set which column I want to insert into the DB?

Example raw data:

{"continent": "Western Europe", "country": "austria", "visa_category": "Entry under European treaties", "traveller_passport": "Latvia"}

DB Model (not including it all as there are getters and setters for each one):

class PassportModel(db.Model):
    __tablename__ = "passports"

    # Country ID specifies which country the passport holder is from.
    id = db.Column(db.Integer, primary_key=True)
    country_id = db.Column(db.Integer, db.ForeignKey("country.id"))
    _european_treaty = db.Column(db.String)
    _remain_indefinitely = db.Column(db.String)
    _days_col_one    = db.Column('7_days', db.String)
    ...

The DB insert query I have attempted:

insert_to_db = PassportModel(country_id=db_country_id, getattr(PassportModel, 'european_treaty')='Value to insert')

Any help is greatly appreciated, thank you.

Tim
  • 3
  • 3

1 Answers1

0

Yes, you can do that by unpacking a kwargs dict.

kwargs = {'european_treaty': 'Value to insert')}

insert_to_db = PassportModel(country_id=db_country_id, **kwargs)
noslenkwah
  • 1,702
  • 1
  • 17
  • 26
  • 1
    Thank you so much! I tried this but I was getting the following error: `TypeError: __init__() keywords must be strings}` Turns out I didn't need to include the getattr function when setting the kwargs so I adjusted your suggestion slightly and it worked: `kwargs = {'european_treaty' : 'Value to insert'}` – Tim Jun 22 '20 at 21:57