当使用filter_by()

时间:2020-08-05 21:34:46

标签: python flask sqlalchemy flask-sqlalchemy

因此,每当我执行Order.query.all()时,返回的结果都是完整的,但是当Order.query.filter_by(id = current_user.id).all()时,我只会得到一个结果。

数据库模型设置:

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), nullable = False)
    email = db.Column(db.String(60), unique = True, nullable = False)
    password = db.Column(db.String(60), nullable = False)
    phone = db.Column(db.Integer, nullable = False)
    country = db.Column(db.String(30), nullable = False)
    city = db.Column(db.String(30), nullable = False)
    address = db.Column(db.String(350), nullable = False)
    kaftl = db.Column(db.String(30), nullable = False)
    order = db.relationship('Order', backref='buyer', lazy=True) 

class Order(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime, nullable = False, default=datetime.utcnow)
    order = db.Column(db.Text, nullable = False)
    kaftl = db.Column(db.Integer, nullable = False)
    price = db.Column(db.Integer, nullable = False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

HTML,以防万一它有用:

{% for order in orders %}
       {{ order.price }}
       {{ order.order }}

   {% endfor %}

1 个答案:

答案 0 :(得分:0)

我认为您应该使用user_id代替id,

Order.query.filter_by(user_id=current_user.id).all()

因为id对于每个对象都是唯一的,所以当您调用该代码时,它实际上会返回id = current_user.id的订单。