Falsk框架实现一对多查询
- 数据库表
- 模型
class Cate(db.Model):
__tablename__ = 'cate'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(15), nullable=False)
# 增加一个字段
brand = db.relationship('Brand', backref='brand')
def __str__(self):
return self.name
class Brand(db.Model):
__tablename__ = 'brand'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(15), nullable=False)
cate_id = db.Column(db.Integer, db.ForeignKey('cate.id'), nullable=False)
def __str__(self):
return self.name
3.实现查询需要注意得点
4.通过商品查询到商品得分类
class AuthorName(fields.Raw):
def format(self, value):
return value.name,value.id
cate_fields = {
'id':fields.Integer,
'name':fields.String,
'cate_id':fields.Integer,
'brand': AuthorName(attribute='brand'),
}
class CateResource(Resource):
@marshal_with(cate_fields)
def get(self):
brands = Brand.query.all()
return brands
api.add_resource(CateResource, '/cate')
5.通过postman测试得到的数据
[
{
"id": 1,
"name": "Java编程",
"cate_id": 1,
"brand": [
"电子书刊",
1
]
},
{
"id": 2,
"name": "mysql优化",
"cate_id": 1,
"brand": [
"电子书刊",
1
]
},
{
"id": 3,
"name": "电饭煲",
"cate_id": 2,
"brand": [
"家用电器",
2
]
},
{
"id": 4,
"name": "欧莱雅",
"cate_id": 3,
"brand": [
"个户化妆",
3
]
},
{
"id": 5,
"name": "小米11",
"cate_id": 4,
"brand": [
"手机通讯",
4
]
}
]