我在类别和产品之间存在多对多关系,如下所示:
category_product = db.Table('category_product',
db.Column('category_id',
db.Integer,
db.ForeignKey('category.id')),
db.Column('product_id',
db.Integer,
db.ForeignKey('product.id')))
class Product(db.Model):
""" SQLAlchemy Product Model """
id = db.Column(db.Integer, primary_key=True)
sku = db.Column(db.String(10), unique=True, nullable=False)
name = db.Column(db.String(80), nullable=False)
categories = db.relationship('Category', secondary=category_product,
backref=db.backref('categories',
lazy='dynamic'))
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Product {}>'.format(self.name)
class Category(db.Model):
""" SQLAlchemy Category Model """
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
products = db.relationship('Product', secondary=category_product,
backref=db.backref('products', lazy='dynamic'))
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Category {}>'.format(self.name)
我正在尝试获取Product
给定的所有对象Category
,由以下指定category_id
:
products = db.session.query(Category).\
filter_by(id=category_id).\
products.\
all()
但是,我得到以下异常:
AttributeError: 'Query' object has no attribute 'products'
我可能错过了一些简单的东西。