2
class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    order = db.relationship('Order', backref='add_order_for_user', lazy='dynamic')

class Order(db.Model):
    __tablename__ = 'orders'

    id = db.Column(db.Integer, primary_key=True)
    product_name = db.Column(db.String(64))
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))

    @classmethod
    def get_all_orders(cls):
        return cls.query.filter_by().all()

I would like to retrieve all the orders, but when i call

Order.get_all_orders()

It return me something like:

|1|carrot|23

Instead of retrieving the user id, I would like his name so i could get

|1|carrot|buyer1

Any help would be greatly appreciated:) thx

EDIT: in sql, that'd be done this way

select orders.id, product_name, users.username from orders, users where orders.user_id = users.id
jthemovie
  • 153
  • 2
  • 13

2 Answers2

0

If you alter your get_all_orders() method to specify which columns you want and specify the filter, you may get what you want. Specifically:

return cls.query(cls.id,cls.product_name,User.username).filter_by(cls.user_id ==User.id).all()

mageliz
  • 146
  • 4
  • 1
    [Querying ... on Flask-SQLAlchemy model gives BaseQuery object is not callable error](https://stackoverflow.com/questions/40918479/querying-with-function-on-flask-sqlalchemy-model-gives-basequery-object-is-not-c) – Ilja Everilä Mar 27 '18 at 05:54
0

Well, not sure if its pretty, but i manage to do it this way:

db.session.query(Order.id, product_name, ,User.username).filter(Order.user_id==User.id).all()

But also this way

Order.query.with_entities(Order.id, product_name, ,User.username).filter(Order.user_id==User.id).all()
jthemovie
  • 153
  • 2
  • 13