我正在尝试使用SQLAlchemy创建一个包含一对多关系的模型。一个食谱可能有许多与之相关的指示。但是,当我尝试实例化配方时,出现TypeError:无法散列的类型:'dict'。如果我删除了directions参数,那么一切都会正常运行,并且它会创建没有任何方向的配方。我是否缺少某些东西,不允许将Directions参数作为列表?
app.py
data = {
'cook_time': 15,
'description': 'Recipe description',
'directions': [{'order': 1, 'text': 'First direction'},
{'order': 2, 'text': 'Second direction'}],
'image_url': 'https://via.placeholder.com/800x300?text=Recipe+Image',
'name': 'Test recipe 2',
'prep_time': 15,
'servings': 6
}
recipe = models.Recipe(
name=data['name'],
description=data['description'],
image_url=data['image_url'],
prep_time=data['prep_time'],
cook_time=data['cook_time'],
servings=data['servings'],
directions=data['directions']
)
models.py
class Recipe(db.Model):
__tablename__ = 'recipes'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200), index=True)
description = db.Column(db.String(2000))
image_url = db.Column(db.String(200))
prep_time = db.Column(db.Integer)
cook_time = db.Column(db.Integer)
servings = db.Column(db.Integer)
directions = db.relationship('RecipeDirection', backref='recipes', lazy='dynamic')
class RecipeDirection(db.Model):
__tablename__ = 'recipe_directions'
id = db.Column(db.Integer, primary_key=True)
recipe_id = db.Column(db.Integer, db.ForeignKey('recipes.id'))
order = db.Column(db.Integer)
text = db.Column(db.String(1000))
最佳答案
因为SQLAlchemy期望将方向指示为RecipeDirection
的列表,所以您收到此错误。要解决此问题,请先创建RecipeDirection
列表。
data = {
'cook_time': 15,
'description': 'Recipe description',
'directions': [{'order': 1, 'text': 'First direction'},
{'order': 2, 'text': 'Second direction'}],
'image_url': 'https://via.placeholder.com/800x300?text=Recipe+Image',
'name': 'Test recipe 2',
'prep_time': 15,
'servings': 6
}
# Create a list of `RecipeDirection`
directions = []
for direction in data.get("directions", []):
directions.append(models.RecipeDirection(**direction))
recipe = models.Recipe(
name=data['name'],
description=data['description'],
image_url=data['image_url'],
prep_time=data['prep_time'],
cook_time=data['cook_time'],
servings=data['servings'],
directions=directions # Now list of RecipieDirection not list of dicts
)
我还建议您研究一个Serilizer,它会为您处理编组和序列化嵌套数据结构的一些细节,例如marshmallow-sqlalchemy
关于python - 尝试实例化具有一对多关系的模型时,Python SQLAlchemy TypeError:不可哈希类型:'dict',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59474637/