0

I'm successfully able to update a row in my SQLAlchemy-driven database (using the answers to How to update SQLAlchemy row entry?). Before I'm happy, I want to do some validation. Specifically, I want to

  • make sure that the field exists in this table (I think I can do this with hasattr)

  • make sure that the field is not a primary key

Community
  • 1
  • 1
ukrutt
  • 2,240
  • 3
  • 20
  • 29
  • sqlalchemy doesn't set up the tables for you, it just issues sql. The fact that the linked answer worked tells you that the field existed (if the field didn't exist, the issued SQL would have thrown an error). The field is only a primary key if you set it up that way when you issued the DDL to create the table. Modifying a row will not issue any DDL or change your schema in any way. – Paul Becotte Jun 01 '16 at 19:10
  • Why do you want to validate the schema? – univerio Jun 01 '16 at 20:32

1 Answers1

0

to extract the list of columns based on ORM class definition:

from sqlalchemy import inspect
mapper = inspect(your_orm_class)
columns = [i.key for i in mapper.attrs]

to extract primary key name based on ORM class definition:

from sqlalchemy.orm import class_mapper
pk = class_mapper(your_orm_class).primary_key[0].name

then modify your validation function / class to check the input against those values.

MOCKBA
  • 1,680
  • 11
  • 19