我在用户的面向公众的个人资料页面上工作,我想在其中显示用户的个人资料以及他们“已发布”的食谱。我有以下 UserSchema,但此模式显示所有配方,包括尚未发布的配方。我只想严格显示已发布的食谱。有没有办法过滤掉尚未发布的食谱?我查看了棉花糖文档,但找不到答案。
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), nullable=False, unique=True)
email = db.Column(db.String(200), nullable=False, unique=True)
password = db.Column(db.String(200))
recipes = db.relationship('Recipe', backref='user')
class UserSchema(Schema):
class Meta:
ordered = True
id = fields.Int(dump_only=True)
username = fields.String(required=True)
email = fields.Email(required=True)
password = fields.Method(required=True)
recipes = fields.Nested("RecipeSchema", many=True, exclude=("author",))
以下是RecipeModel 和RecipeSchema,
class Recipe(db.Model):
__tablename__ = 'recipe'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
description = db.Column(db.String(200))
is_publish = db.Column(db.Boolean(), default=False)
user_id = db.Column(db.Integer(), db.ForeignKey("user.id"))
class RecipeSchema(Schema):
class Meta:
ordered = True
id = fields.Integer(dump_only=True)
name = fields.String(required=True, validate=[validate.Length(max=100)])
description = fields.String(validate=[validate.Length(max=200)])
is_publish = fields.Boolean(dump_only=True)
author = fields.Nested(UserSchema, attribute='user', dump_only=True, exclude=('email', ))
负责返回用户配置文件数据的资源是:
from schemas.user import UserSchema
user_schema = UserSchema()
class UserResource(Resource):
@classmethod
def get(cls, _id: int):
user = User.query.filter_by(id=_id).first()
if not user:
return {"message": gettext("user_not_found")}, 404
return user_schema.dump(user), 200
电流输出为
{
"id": "1",
"username": "john.doe",
"recipes": [
{
"id": "1",
"name": "cheese pizza",
"description": "yummy",
"is_publish": true
},
{
"id": "2",
"name": "Potato Salad",
"description": "tags with sepearate function",
"is_publish": false
}
]
}
我希望它是
{
"id": "1",
"username": "john.doe",
"recipes": [
{
"id": "1",
"name": "cheese pizza",
"description": "yummy",
"is_publish": true
}
]
}