FloatingRock
FloatingRock

Reputation: 7065

SQLAlchemy: Populate instance attributes from Database query

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.

Upvotes: 0

Views: 1601

Answers (1)

Oleh Prypin
Oleh Prypin

Reputation: 34116

For this particular case you can use get which gets a row by its primary key:

u = User.get(1)
u.id, u.name, u.email

The problem with your code is that you're trying to use a bound method, even worse, the constructor (in which assigning to self does nothing at all) to get an existing, completely different instance.

I'll just show a reimplementation of the get method so you can reuse it for other cases.

class User(db.Model):
    # ...

    @classmethod
    def get_by_id(cls, id):
        return cls.query.filter_by(id=id).one()


u = User.get_by_id(1)

Upvotes: 1

Related Questions