I'm using SQLAlchemy with the below User
model to track users on my site. I'm trying to get the __init__
method to populate all of the fields in the class instance once it's passed a valid user id
, but it doesn't work like it's supposed to.
Here's my 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 the fields
u = User.query.filter_by(id=id).first()
# Fill in the name, email fields from the result
self = u # <-- Not working as expected
# ...
The problem is that the attributes are not getting populated.
u = User(1)
u.id, u.name, u.email # <-- Output: None
How can I auto-populate all the class attributes from the user id
without having to set them one by one?
Note: I've removed the validation bits from the above code to avoid clutter Note2: I'm a beginner in SQLAlchemy, and just recently started using Python.
classmethod
s,staticmethod
s) – Dan Getz Jun 22 at 15:52