Search code examples
pythondjangoormsqlalchemypeewee

Python ORMs with attribute constraints such as required / optional?


Here's what Pony ORM can do:

class Business(db.Entity):
    name        = Required(str)
    latitude    = Optional(float, py_check=lambda val: -90 <= val <= 90)
    longitude   = Optional(float, py_check=lambda val: -180 <= val <= 180)

I'm trying to determine if any of the others (SQLAlchemy, SQLObject, etc.) can do this. And especially, those that can be used as a library in a framework. (So, I'm not sure how much work it'd be to use the Django ORM in a non-Django app.)

I'm having a hard time finding this feature in the various docs, but I'm sure they support it.

So my question: Do these (or other) ORMs support required vs. optional attributes and validations? If so, how?

  • SQLAlchemy
  • SQLObject
  • Storm
  • Django
  • Peewee

Solution

  • Using SQLAlchemy: Yes

    • Required/Optional is done by setting nullable = False/True
    • Validations are done using Simple Validators

    The code below uses Flask, but pure sqlalchemy code is almost the same:

    class Business(db.Model):
        __tablename__ = 'business'
        id = db.Column(db.Integer, primary_key=True)
    
        name = db.Column(db.String, nullable=False)
        latitude = db.Column(db.Float, nullable=True)
        longitude = db.Column(db.Float, nullable=True)
    
        @db.validates('latitude')
        def validate_lat(self, key, value):
            assert value is None or (-90 <= value <= 90)
            return value
    
        @db.validates('longitude')
        def validate_lon(self, key, value):
            assert value is None or (-180 <= value <= 180)
            return value
    

    As already noted by @kevin-christopher-henry, there is little point using Django ORM with non-Django framework, as well as the other way around: if you use Django, it is much easier to stick to Django ORM.