python - SQLAlchemy: Populate instance attributes from Database query -
python - SQLAlchemy: Populate instance attributes from Database query -
i'm using sqlalchemy below user
model track users on site. i'm trying __init__
method populate of fields in class instance 1 time it's passed valid user id
, doesn't work it's supposed to.
here's code:
class user(db.model): # fields id = db.column(db.integer, primary_key=true) name = db.column(db.string(32)) email = db.column(db.string(255), index=true) # methods def __init__(self, id): # populate fields u = user.query.filter_by(id=id).first() # fill in name, email fields result self = u # <-- not working expected # ...
the problem attributes not getting populated.
u = user(1) u.id, u.name, u.email # <-- output: none
how can auto-populate class attributes user id
without having set them 1 one?
note: i've removed validation bits above code avoid clutter note2: i'm beginner in sqlalchemy, , started using python.
for particular case can utilize get
gets row primary key:
u = user.get(1) u.id, u.name, u.email
the problem code you're trying utilize bound method, worse, constructor (in assigning self
nil @ all) existing, different instance.
i'll show reimplementation of get
method can reuse other cases.
class user(db.model): # ... @classmethod def get_by_id(cls, id): homecoming cls.query.filter_by(id=id).one() u = user.get_by_id(1)
python sqlalchemy flask-sqlalchemy
Comments
Post a Comment