我是python的初学者,我目前正在对餐厅进行api分组。
问题在于当我加入两个餐桌餐厅和地址时,查询SQLAlchemy向我发送了2个元组,但是我想合并他的元组
我的两个班级:餐厅和地址地址
class Restaurants(db.Model):
__tablename__ = 'restaurants'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
description = db.Column(db.String(255))
creation = db.Column(db.DateTime)
opening = db.Column(db.DateTime)
closing = db.Column(db.DateTime)
url = db.Column(db.String(255))
rank = db.Column(db.Integer)
adresse = db.relationship('Adresse', uselist=False, backref='adresse')
class Adresse(db.Model):
__tablename__ = 'adresse'
id = db.Column(db.Integer, primary_key=True)
city= db.Column(db.String(255))
postal_code = db.Column(db.String(255))
street = db.Column(db.String(255))
restaurant_id = db.Column(db.Integer, ForeignKey('restaurants.id'))
long = db.Column(db.Float)
lat = db.Column(db.Float)enter code here
文件restaurant.py
fields = {
'id': fields.Integer,
'name': fields.String,
'city': fields.String,
'street': fields.String,
'postal code': fields.String(attribute='postal_code'),
'description': fields.String,
'opening time': fields.String(attribute='opening'),
'closing time': fields.String(attribute='closing'),
'picture': fields.String(attribute='url'),
'rank': fields.Integer
}
测试01:
@marshal_with(fields)
def get(self)
resto = session.query(Restaurants).join(Adresse, Restaurants.id == Adresse.restaurant_id).all()
return resto, 201
结果:
{
"id": 1,
"name": "Hugiz",
"city": null,
"address": null,
"postal code": null,
"description": "Fastfood",
"opening time": "9:00",
"closing time": "18:00",
"picture": null,
"rank": 4
}
测试02:
@marshal_with(fields)
def get(self)
resto = session.query(Restaurants, Adresse).filter(Restaurants.id == Adresse.restaurant_id).all()
return resto, 201
结果:
[
{
"id": 1,
"name": "Hugiz",
"city": null,
"address": null,
"postal code": null,
"description": "Fastfood",
"opening time": "9:00",
"closing time": "18:00",
"picture": null,
"rank": 4
},
{
"id": 1,
"name": null,
"city": "Paris",
"address": "1-3 Rue de Savies",
"postal code": "75020",
"description": null,
"opening time": null,
"closing time": null,
"picture": null,
"rank": 0
}
]
测试3:
@marshal_with(champs_restaurant)
def get(self):
resto = session.query(Restaurants).outerjoin(Adresse)
for restaurant in resto:
resto.id = restaurant.id
resto.name = restaurant.name
resto.city = restaurant.adresse.city
resto.street = restaurant.adresse.street
resto.postal_code = restaurant.adresse.postal_code
resto.description = restaurant.description
resto.opening = restaurant.opening
resto.closing = restaurant.closing
resto.url = restaurant.url
resto.rank = restaurant.rank
return resto, 201
结果:
{
"id": 2,
"name": "hugiz",
"city": "Paris",
"address": "1-3 rue de Savies",
"postal code": "75020",
"description": "Fastfood",
"opening time": "9:00",
"closing time": "18:00",
"picture": null,
"rank": 4
}
这个结果很好,但是只需要最后一家餐厅。 但是我想在查询末尾添加.all()
最后,我将喜欢一个合并我的测试02的查询,以便没有两个对象