Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7090471
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T08:03:31+00:00 2026-05-28T08:03:31+00:00

Using the SQLAlchemy ORM, I want to make sure values are the right type

  • 0

Using the SQLAlchemy ORM, I want to make sure values are the right type for their columns.

For example, say I have an Integer column. I try to insert the value “hello”, which is not a valid integer. SQLAlchemy will allow me to do this. Only later, when I execute session.commit(), does it raise an exception: sqlalchemy.exc.DataError: (DataError) invalid input syntax integer: "hello"….

I am adding batches of records, and I don’t want to commit after every single add(…), for performance reasons.

So how can I:

  • Raise the exception as soon as I do session.add(…)
  • Or, make sure the value I am inserting can be converted to the target Column datatype, before adding it to the batch?
  • Or any other way to prevent one bad record from spoiling an entire commit().
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T08:03:32+00:00Added an answer on May 28, 2026 at 8:03 am

    SQLAlchemy doesn’t build this in as it defers to the DBAPI/database as the best and most efficient source of validation and coercion of values.

    To build your own validation, usually TypeDecorator or ORM-level validation is used. TypeDecorator has the advantage that it operates at the core and can be pretty transparent, though it only occurs when SQL is actually emitted.

    To do validation and coercion sooner, this is at the ORM level.

    Validation can be ad-hoc, at the ORM layer, via @validates:

    http://docs.sqlalchemy.org/en/latest/orm/mapped_attributes.html#simple-validators

    The event system that @validates uses is also available directly. You can write a generalized solution that links validators of your choosing to the types being mapped:

    from sqlalchemy import Column, Integer, String, DateTime
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import event
    import datetime
    
    Base= declarative_base()
    
    def validate_int(value):
        if isinstance(value, basestring):
            value = int(value)
        else:
            assert isinstance(value, int)
        return value
    
    def validate_string(value):
        assert isinstance(value, basestring)
        return value
    
    def validate_datetime(value):
        assert isinstance(value, datetime.datetime)
        return value
    
    validators = {
        Integer:validate_int,
        String:validate_string,
        DateTime:validate_datetime,
    }
    
    # this event is called whenever an attribute
    # on a class is instrumented
    @event.listens_for(Base, 'attribute_instrument')
    def configure_listener(class_, key, inst):
        if not hasattr(inst.property, 'columns'):
            return
        # this event is called whenever a "set" 
        # occurs on that instrumented attribute
        @event.listens_for(inst, "set", retval=True)
        def set_(instance, value, oldvalue, initiator):
            validator = validators.get(inst.property.columns[0].type.__class__)
            if validator:
                return validator(value)
            else:
                return value
    
    
    class MyObject(Base):
        __tablename__ = 'mytable'
    
        id = Column(Integer, primary_key=True)
        svalue = Column(String)
        ivalue = Column(Integer)
        dvalue = Column(DateTime)
    
    
    m = MyObject()
    m.svalue = "ASdf"
    
    m.ivalue = "45"
    
    m.dvalue = "not a date"
    

    Validation and coercion can also be built at the type level using TypeDecorator, though this is only when SQL is being emitted, such as this example which coerces utf-8 strings to unicode:

    http://docs.sqlalchemy.org/en/latest/core/custom_types.html#coercing-encoded-strings-to-unicode

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm using the SQLAlchemy Python ORM in a Pylons project. I have a class
I'm using SQLalchemy for a Python project, and I want to have a tidy
I'm using sqlalchemy 6.0. The SQL Server T-SQL dialect seems to want to make
I access a a postgres table using SQLAlchemy. I want a query to have
I create a table in database using sqlalchemy and now want to make a
I'm using __init__() like this in some SQLAlchemy ORM classes that have many parameters
We're using SQLAlchemy declarative base and I have a method that I want isolate
I'm using an ORM (SQLAlchemy, but my question is quite implementation-agnostic) to model a
I've been trying to map an object to a database using SQLAlchemy but have
I have been using django ORM, it's nice and very easy, but this time

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.