我正在为Angular前端编写Flask API,我的配方类返回JSON,其中包含有关配方的所有信息,但我只需要返回一些配方列表信息即可使其更快地加载,还需要返回所有信息以获取配方详细信息。
所以
@classmethod
def find_all(cls):
return cls.query.order_by(cls.time_added.desc()).all()
应仅返回ID,名称,描述JSON
和
def find_by_id(cls, _id):
return cls.query.filter_by(id=_id).first()
应返回包含食谱所有信息的JSON。
什么是最佳解决方案?两个不同的类,或者有什么不错的方法吗?
非常感谢您的帮助。
我的食谱模型:
class RecipeModel(db.Model):
__tablename__ = 'recipes'
# create recipe table
id = db.Column(db.Integer, primary_key=True, )
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
cuisine_id = db.Column(db.Integer, db.ForeignKey('cuisine.id'))
name = db.Column(db.String(150))
description = db.Column(db.Text)
image_path = db.Column(db.String(100))
total_time = db.Column(db.Integer)
prep_time = db.Column(db.Integer)
cook_time = db.Column(db.Integer)
level = db.Column(db.String(45))
source = db.Column(db.String(45))
rating = db.Column(db.DECIMAL(3, 2))
time_added = db.Column(db.Date)
def __init__(self, user_id, cuisine_id, name, description, image_path, total_time, prep_time, cook_time, level,
source, ):
self.user_id = user_id
self.cuisine_id = cuisine_id
self.name = name
self.description = description
self.image_path = image_path
self.total_time = total_time
self.prep_time = prep_time
self.cook_time = cook_time
self.level = level
self.source = source
# Return recipe as JSON object
def json(self):
return {
'id': self.id,
'name': self.name,
'cuisine_id': self.cuisine_id,
'description': self.description,
'image_path': self.image_path,
'total_time': self.total_time,
'prep_time': self.prep_time,
'cook_time': self.cook_time,
'level': self.level,
'source': self.source,
}
# Find recipe by ID
@classmethod
def find_by_id(cls, _id):
return cls.query.filter_by(id=_id).first()
# Find all recipes
@classmethod
def find_all(cls):
return cls.query.order_by(cls.time_added.desc()).all()
我的资源:
class RecipesList(Resource):
@classmethod
def get(cls):
return {'recipes': [recipes.json() for recipes in RecipeModel.find_all()]}
答案 0 :(得分:0)
不要在模型上使用.json()
,而是将序列化器分成两个(或根据需要)执行两种不同类型的序列化的函数(或者您可以使用mode='detail'
参数化单个序列化函数等等。
def serialize_recipe_list(recipe):
return {"id": recipe.id}
def serialize_recipe_detail(recipe):
return {"id": recipe.id, "more": here}
class RecipesList(Resource):
@classmethod
def get(cls):
return {
"recipes": [
serialize_recipe_list(recipe)
for recipe in RecipeModel.find_all()
]
}
class RecipesDetail(Resource):
@classmethod
def get(cls, id):
recipe = RecipeModel.find_by_id(id)
return serialize_recipe_detail(recipe)