Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are SQLAlchemy model variables class or object type?

I am learning Web Development in Flask. I am using SQLAlchemy. A typical database object is structured like so:

class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    default = db.Column(db.Boolean, default=False, index=True)
    permissions = db.Column(db.Integer)
    users = db.relationship('User', backref='role', lazy='dynamic')

    def __repr__(self):
        return '<Role %r>' % self.name

My question is, are these all class variables or object variables? They are outside the __init__ so it would seem they are class variables, that seems odd though. Any pointers on this would be great! Thanks!

like image 266
KexAri Avatar asked Mar 10 '23 08:03

KexAri


1 Answers

The fields with type Column in Role are indeed class variables. But they would be replaced with InstrumentedAttribute during Role construction, which occurred in declarative.aqi.DeclarativeMeta.__init__()

This is why we define Role inherited from Base with metaclass declarative.aqi.DeclarativeMeta (the return value of declarative_base())

The InstrumentedAttribute is a data descriptor, which defined __get__ and __set__ applied to instance dictionary. As a result, we could use them to do operation through instance.

In the following example, r.name is a data descriptor, r.name = 'hello' is equivalent to Role.name.__set__(r, 'hello') -> r.__dict__['name'] = 'hello'

r = Role()
r.name = 'hello'
like image 144
Jacky1205 Avatar answered Mar 27 '23 03:03

Jacky1205